"""
智能电商平台 - 整合版
包含客服助手、商品推荐、用户管理等功能
"""

import streamlit as st
import json
import hashlib
import uuid
import time
import requests
from datetime import datetime
from pathlib import Path
from typing import Dict, Any, List, Optional
import sys
import os
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import jieba

# 版本信息
VERSION = "v1.1.3"

# 添加smart_assistant路径到sys.path
project_root = Path(__file__).parent
smart_assistant_path = project_root / "smart_assistant"
sys.path.insert(0, str(smart_assistant_path))

# 添加积分系统路径到sys.path
utils_path = project_root / "utils"
sys.path.insert(0, str(utils_path))

# 导入会员系统
try:
    from utils.membership_system import (
        get_user_membership, 
        update_user_membership,
        check_discount_eligibility,
        check_free_shipping_eligibility,
        grant_vip_membership
    )
    from utils.membership_ui import (
        show_membership_center,
        show_compact_membership_info,
        show_membership_discount_info
    )
    MEMBERSHIP_AVAILABLE = True
    print("✅ 会员系统加载成功")
except ImportError as e:
    print(f"⚠️ 会员系统导入失败: {e}")
    MEMBERSHIP_AVAILABLE = False

# 加载环境变量
def load_environment_variables():
    """加载环境变量"""
    # 尝试从多个位置加载环境变量
    env_files = [
        project_root / ".env",
        Path.cwd() / ".env"
    ]
    
    dotenv_loaded = False
    
    try:
        from dotenv import load_dotenv
        
        for env_file in env_files:
            if env_file.exists():
                load_dotenv(env_file)
                dotenv_loaded = True
                print(f"从 {env_file} 加载环境变量")
                break
        
        if not dotenv_loaded:
            print("未找到 .env 文件，使用默认配置")
            
    except ImportError:
        print("python-dotenv 未安装，使用默认配置")
        dotenv_loaded = False
    
    # 设置默认环境变量（如果没有设置）
    default_env = {
        "SILICONFLOW_API_KEY": "sk-nvmyeqrurhtqrhyddcmyhqlsczsluagkkhfucoxtobfqnnid",
        "SILICONFLOW_API_BASE": "https://api.siliconflow.cn/v1",
        "DEFAULT_MODEL": "deepseek-ai/DeepSeek-R1-0528-Qwen3-8B",
        "DEFAULT_TEMPERATURE": "0.7"
    }
    
    for key, value in default_env.items():
        if not os.environ.get(key):
            os.environ[key] = value
    
    return dotenv_loaded

# 加载环境变量
DOTENV_AVAILABLE = load_environment_variables()

# 导入智能客服助手
try:
    # 设置环境变量（如果dotenv不可用）
    if not DOTENV_AVAILABLE:
        os.environ.setdefault("SILICONFLOW_API_KEY", "sk-nvmyeqrurhtqrhyddcmyhqlsczsluagkkhfucoxtobfqnnid")
        os.environ.setdefault("SILICONFLOW_API_BASE", "https://api.siliconflow.cn/v1")
        os.environ.setdefault("DEFAULT_MODEL", "deepseek-ai/DeepSeek-R1-0528-Qwen3-8B")
        os.environ.setdefault("DEFAULT_TEMPERATURE", "0.7")
    
    from assistant.core import SmartAssistant
    from assistant.tools import CustomerServiceSession
    AI_ASSISTANT_AVAILABLE = True
    print("✅ AI助手模块加载成功")
except ImportError as e:
    print(f"⚠️ 无法导入AI助手: {e}")
    AI_ASSISTANT_AVAILABLE = False
    
    # 创建备用的CustomerServiceSession类
    class CustomerServiceSession:
        def __init__(self, session_id):
            self.session_id = session_id
            self.messages = []
        
        def add_message(self, content, role):
            self.messages.append({"role": role, "content": content, "timestamp": datetime.now().isoformat()})
    
    # 创建备用的SmartAssistant类
    class SmartAssistant:
        def __init__(self):
            self.name = "基础客服助手"
        
        def chat(self, user_input, use_tools=True, show_thinking=False):
            return "抱歉，AI助手暂时不可用，请稍后再试或联系人工客服。"

# 创建本地Ollama版本的AI助手
class LocalOllamaAssistant:
    """使用本地Ollama的AI助手"""
    
    def __init__(self):
        self.name = "本地AI助手"
        self.ollama_base_url = os.environ.get("OPENAI_API_BASE", "http://localhost:11434")
        self.ollama_model = "deepseek-r1:latest"  # 使用实际可用的模型
        self.available = self._test_connection()
    
    def _test_connection(self):
        """测试Ollama连接"""
        try:
            response = requests.get(f"{self.ollama_base_url}/api/tags", timeout=5)
            if response.status_code == 200:
                models_data = response.json()
                available_models = [model['name'] for model in models_data.get('models', [])]
                
                # 检查是否有deepseek模型可用
                if available_models:
                    # 优先使用deepseek模型
                    for model_name in available_models:
                        if 'deepseek' in model_name.lower():
                            self.ollama_model = model_name
                            break
                    else:
                        self.ollama_model = available_models[0]  # 使用第一个可用模型
                    
                    print(f"✅ 本地AI助手连接成功 | model = {self.ollama_model}")
                    return True
                    
            return False
        except Exception as e:
            print(f"⚠️ 本地AI助手连接失败: {e}")
            return False
    
    def chat(self, user_input, use_tools=True, show_thinking=False):
        """使用本地Ollama进行对话"""
        if not self.available:
            return "本地AI助手暂时不可用，请稍后再试。"
        
        try:
            # 构建针对deepseek-r1模型的提示词
            system_prompt = """你是一个专业的电商平台客服助手。请直接回答用户问题，不要显示思考过程。

回答规则：
1. 回答要简洁明了，2-3句话即可
2. 如果涉及订单问题，建议用户查看订单管理页面
3. 如果涉及商品推荐，建议用户查看推荐页面
4. 保持专业和礼貌的态度
5. 直接给出答案，不要包含任何思考标签或过程"""
            
            prompt = f"{system_prompt}\n\n用户问题：{user_input}\n\n客服回答："
            
            # 使用流式API
            response = requests.post(
                f"{self.ollama_base_url}/api/generate",
                json={
                    "model": self.ollama_model,
                    "prompt": prompt,
                    "temperature": 0.7,
                    "stream": True,  # 启用流式输出
                    "options": {
                        "num_predict": 200,  # 限制输出长度
                        "stop": ["用户问题：", "客服回答：", "\n\n用户", "\n\n客服"]
                    }
                },
                timeout=30,
                stream=True
            )
            
            if response.status_code == 200:
                full_response = ""
                thinking_content = ""
                in_thinking = False
                actual_response = ""
                
                # 处理流式响应
                for line in response.iter_lines():
                    if line:
                        try:
                            data = json.loads(line)
                            token = data.get("response", "")
                            
                            if token:
                                full_response += token
                                
                                # 检测思考标签
                                if "<think>" in token:
                                    in_thinking = True
                                    thinking_content += token
                                elif "</think>" in token:
                                    in_thinking = False
                                    thinking_content += token
                                    # 思考结束，后续内容为实际回答
                                elif in_thinking:
                                    thinking_content += token
                                else:
                                    # 不在思考过程中，这是实际回答
                                    actual_response += token
                                    
                            # 如果响应完成
                            if data.get("done", False):
                                break
                                
                        except json.JSONDecodeError:
                            continue
                
                # 处理完整响应
                if "</think>" in full_response:
                    # 提取思考标签后的内容
                    parts = full_response.split("</think>")
                    if len(parts) > 1:
                        actual_response = parts[-1].strip()
                    else:
                        actual_response = full_response.strip()
                else:
                    actual_response = full_response.strip()
                
                # 清理响应内容
                actual_response = self._clean_response(actual_response)
                
                # 如果回复太短或为空，使用备用回复
                if len(actual_response) < 5:
                    return self._generate_fallback_response(user_input)
                
                return actual_response
            else:
                print(f"Ollama API错误: {response.status_code}")
                return self._generate_fallback_response(user_input)
                
        except Exception as e:
            print(f"本地AI助手错误: {e}")
            return self._generate_fallback_response(user_input)
    
    def _clean_response(self, response):
        """清理响应内容"""
        # 移除可能的思考标签
        if "<think>" in response:
            response = response.split("<think>")[0].strip()
        
        # 移除可能的提示词残留
        unwanted_patterns = [
            "用户问题：", "客服回答：", "请回答：", "回答：",
            "根据提示", "作为", "系统提示", "规则："
        ]
        
        for pattern in unwanted_patterns:
            if pattern in response:
                parts = response.split(pattern)
                if len(parts) > 1:
                    response = parts[-1].strip()
        
        # 移除多余的换行和空格
        response = response.strip()
        
        # 如果响应以引号开始和结束，移除引号
        if response.startswith('"') and response.endswith('"'):
            response = response[1:-1].strip()
        
        return response
    
    def chat_stream(self, user_input, container=None):
        """流式对话，实时显示回复"""
        if not self.available:
            return "本地AI助手暂时不可用，请稍后再试。"
        
        try:
            # 构建针对deepseek-r1模型的提示词
            system_prompt = """你是一个专业的电商平台客服助手。请直接回答用户问题，不要显示思考过程。

回答规则：
1. 回答要简洁明了，2-3句话即可
2. 如果涉及订单问题，建议用户查看订单管理页面
3. 如果涉及商品推荐，建议用户查看推荐页面
4. 保持专业和礼貌的态度
5. 直接给出答案，不要包含任何思考标签或过程"""
            
            prompt = f"{system_prompt}\n\n用户问题：{user_input}\n\n客服回答："
            
            # 使用流式API
            response = requests.post(
                f"{self.ollama_base_url}/api/generate",
                json={
                    "model": self.ollama_model,
                    "prompt": prompt,
                    "temperature": 0.7,
                    "stream": True,
                    "options": {
                        "num_predict": 200,
                        "stop": ["用户问题：", "客服回答：", "\n\n用户", "\n\n客服"]
                    }
                },
                timeout=30,
                stream=True
            )
            
            if response.status_code == 200:
                full_response = ""
                in_thinking = False
                actual_response = ""
                
                # 创建容器显示流式回复
                if container:
                    message_placeholder = container.empty()
                
                # 处理流式响应
                for line in response.iter_lines():
                    if line:
                        try:
                            data = json.loads(line)
                            token = data.get("response", "")
                            
                            if token:
                                full_response += token
                                
                                # 检测思考标签
                                if "<think>" in token:
                                    in_thinking = True
                                elif "</think>" in token:
                                    in_thinking = False
                                    # 思考结束，开始显示实际回答
                                    actual_response = ""
                                elif not in_thinking:
                                    # 不在思考过程中，这是实际回答
                                    actual_response += token
                                    
                                    # 实时更新显示
                                    if container and actual_response.strip():
                                        cleaned_response = self._clean_response(actual_response)
                                        if cleaned_response:
                                            message_placeholder.markdown(f"""
                                            <div style="text-align: left; margin: 0.5rem 0;">
                                                <div style="background: #f8f9fa; color: #333; padding: 0.5rem 1rem; 
                                                           border-radius: 15px; display: inline-block; max-width: 70%;">
                                                    🤖 {cleaned_response}
                                                </div>
                                            </div>
                                            """, unsafe_allow_html=True)
                                    
                            # 如果响应完成
                            if data.get("done", False):
                                break
                                
                        except json.JSONDecodeError:
                            continue
                
                # 处理完整响应
                if "</think>" in full_response:
                    parts = full_response.split("</think>")
                    if len(parts) > 1:
                        actual_response = parts[-1].strip()
                else:
                    actual_response = full_response.strip()
                
                # 清理响应内容
                actual_response = self._clean_response(actual_response)
                
                # 如果回复太短或为空，使用备用回复
                if len(actual_response) < 5:
                    return self._generate_fallback_response(user_input)
                
                return actual_response
            else:
                print(f"Ollama API错误: {response.status_code}")
                return self._generate_fallback_response(user_input)
                
        except Exception as e:
            print(f"本地AI助手错误: {e}")
            return self._generate_fallback_response(user_input)
    
    def _generate_fallback_response(self, user_input):
        """生成备用回复"""
        user_input_lower = user_input.lower()
        
        if "订单" in user_input_lower:
            return "您好！关于订单问题，请您前往【订单管理】页面查看详细信息。如有其他问题，我随时为您服务。"
        elif "推荐" in user_input_lower or "商品" in user_input_lower:
            return "我为您推荐商品！请前往【商品推荐】页面查看个性化推荐，那里有很多适合您的商品。"
        elif "退款" in user_input_lower:
            return "关于退款事宜，您可以在订单详情页面提交退款申请，一般3-5个工作日内处理完成。"
        elif "个人" in user_input_lower or "信息" in user_input_lower:
            return "您可以在【个人中心】页面修改和查看个人信息。如需帮助，我随时为您解答。"
        else:
            return "感谢您的咨询！我是您的专属客服助手，如有任何问题请随时联系我。"

# 页面配置
st.set_page_config(
    page_title=f"智能电商平台 {VERSION}",
    page_icon="🛒",
    layout="wide",
    initial_sidebar_state="expanded",
    menu_items={
        'Get Help': None,
        'Report a bug': None,
        'About': None
    }
)

# 数据文件路径
PROJECT_ROOT = Path(__file__).parent
DATA_DIR = PROJECT_ROOT / "data"
USERS_FILE = DATA_DIR / "users.json"
ORDERS_FILE = DATA_DIR / "orders.json"
GOODS_FILE = DATA_DIR / "goods.json"
RECOMMENDATION_USERS_FILE = DATA_DIR / "recommendation_users.json"

# 推荐服务API地址
RECOMMENDATION_API = "http://localhost:8000"

# CSS样式 - 现代化电商平台设计
st.markdown("""
<style>
    /* 导入现代字体 */
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
    
    /* 全局样式重置和优化 */
    * {
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    }
    
    .main .block-container {
        padding-top: 0.5rem;
        padding-bottom: 1rem;
        max-width: 1400px;
        margin: 0 auto;
    }
    
    /* 隐藏默认Streamlit元素 */
    #MainMenu {visibility: hidden;}
    footer {visibility: hidden;}
    .stDeployButton {display: none;}
    header[data-testid="stHeader"] {display: none;}
    
    /* 顶部导航栏 - 京东红配色方案 */
    .top-header {
        background: linear-gradient(135deg, #e3000b 0%, #ff4757 50%, #ff6b35 100%);
        color: white;
        padding: 1rem 1.5rem;
        border-radius: 0;
        margin: -1rem -1rem 1.5rem -1rem;
        box-shadow: 0 4px 20px rgba(227, 0, 11, 0.2);
        position: sticky;
        top: 0;
        z-index: 1000;
        backdrop-filter: blur(10px);
    }
    
    .top-header h1 {
        margin: 0;
        font-size: 1.6rem;
        font-weight: 700;
        text-shadow: 1px 1px 3px rgba(0,0,0,0.3);
        letter-spacing: -0.5px;
    }
    
    .top-header .subtitle {
        margin: 0.3rem 0 0 0;
        font-size: 0.9rem;
        opacity: 0.9;
        font-weight: 400;
    }
    
    /* 面包屑导航 */
    .breadcrumb {
        background: #f8f9fa;
        padding: 0.8rem 1rem;
        border-radius: 8px;
        margin-bottom: 1rem;
        font-size: 0.85rem;
        color: #666;
    }
    
    .breadcrumb a {
        color: #e3000b;
        text-decoration: none;
    }
    
    /* 用户信息卡片 - 现代化设计 */
    .user-info {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 1.5rem;
        border-radius: 16px;
        margin-bottom: 1.5rem;
        box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
        border: none;
        position: relative;
        overflow: hidden;
    }
    
    .user-info::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -50%;
        width: 100%;
        height: 100%;
        background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
        animation: float 6s ease-in-out infinite;
    }
    
    .user-info h3 {
        margin: 0 0 0.8rem 0;
        font-size: 1.2rem;
        font-weight: 600;
        position: relative;
        z-index: 2;
    }
    
    .user-info p {
        margin: 0;
        font-size: 0.9rem;
        opacity: 0.95;
        position: relative;
        z-index: 2;
    }
    
    /* 状态卡片 - 电商平台风格 */
    .status-card {
        background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
        color: white;
        padding: 1.2rem;
        border-radius: 12px;
        text-align: center;
        box-shadow: 0 4px 16px rgba(255, 107, 53, 0.25);
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }
    
    .status-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 25px rgba(255, 107, 53, 0.35);
    }
    
    .status-card-secondary {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        color: white;
        padding: 1.2rem;
        border-radius: 12px;
        text-align: center;
        box-shadow: 0 4px 16px rgba(40, 167, 69, 0.25);
        transition: all 0.3s ease;
    }
    
    .status-card-secondary:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 25px rgba(40, 167, 69, 0.35);
    }
    
    .status-card-points {
        background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
        color: #212529;
        padding: 1.2rem;
        border-radius: 12px;
        text-align: center;
        box-shadow: 0 4px 16px rgba(255, 193, 7, 0.25);
        transition: all 0.3s ease;
    }
    
    .status-card-points:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 25px rgba(255, 193, 7, 0.35);
    }
    
    /* 商品卡片 - 现代化电商设计 */
    .product-card {
        background: white;
        border-radius: 16px;
        padding: 1.5rem;
        margin: 0.8rem 0;
        box-shadow: 0 2px 12px rgba(0,0,0,0.08);
        border: 1px solid #f0f2f5;
        min-height: 200px;
        transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        position: relative;
        overflow: hidden;
    }
    
    .product-card:hover {
        box-shadow: 0 8px 30px rgba(0,0,0,0.12);
        transform: translateY(-6px);
        border-color: #e3000b;
    }
    
    .product-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, #e3000b, #ff6b35, #ffc107);
        transform: scaleX(0);
        transition: transform 0.4s ease;
    }
    
    .product-card:hover::before {
        transform: scaleX(1);
    }
    
    .product-card h5 {
        margin: 0 0 0.8rem 0;
        font-size: 1.1rem;
        font-weight: 600;
        line-height: 1.4;
        color: #2c3e50;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }
    
    .product-card p {
        margin: 0.4rem 0;
        font-size: 0.9rem;
        line-height: 1.5;
        color: #7f8c8d;
    }
    
    /* 商品标签 */
    .product-tag {
        display: inline-block;
        background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
        color: white;
        padding: 0.2rem 0.6rem;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 500;
        margin: 0.2rem 0.2rem 0 0;
    }
    
    /* 价格显示 - 电商风格 */
    .price-badge {
        background: linear-gradient(135deg, #e3000b 0%, #ff6b35 100%);
        color: white;
        padding: 0.4rem 1rem;
        border-radius: 20px;
        font-size: 1.1rem;
        font-weight: 700;
        box-shadow: 0 4px 12px rgba(227, 0, 11, 0.3);
        display: inline-block;
        position: relative;
    }
    
    .price-badge::before {
        content: '¥';
        font-size: 0.8em;
        margin-right: 0.2rem;
    }
    
    .price-original {
        text-decoration: line-through;
        color: #95a5a6;
        font-size: 0.85rem;
        margin-left: 0.8rem;
        font-weight: 400;
    }
    
    /* 折扣标签 */
    .discount-badge {
        background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
        color: white;
        padding: 0.2rem 0.5rem;
        border-radius: 8px;
        font-size: 0.75rem;
        font-weight: 600;
        position: absolute;
        top: 10px;
        right: 10px;
    }
    
    /* 购物车相关样式 */
    .cart-card {
        background: linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%);
        border-radius: 16px;
        padding: 1.5rem;
        margin: 0.8rem 0;
        border-left: 5px solid #ffc107;
        box-shadow: 0 4px 16px rgba(255, 193, 7, 0.2);
        transition: all 0.3s ease;
    }
    
    .cart-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(255, 193, 7, 0.3);
    }
    
    /* 结算卡片 */
    .checkout-card {
        background: linear-gradient(135deg, #e8f4fd 0%, #bee5eb 100%);
        border-radius: 16px;
        padding: 1.8rem;
        margin: 1rem 0;
        border-left: 5px solid #17a2b8;
        box-shadow: 0 4px 16px rgba(23, 162, 184, 0.2);
    }
    
    /* 订单卡片 - 现代化设计 */
    .order-card {
        background: white;
        border-radius: 16px;
        padding: 1.5rem;
        margin: 1rem 0;
        border-left: 5px solid #007bff;
        box-shadow: 0 4px 16px rgba(0,0,0,0.08);
        transition: all 0.3s ease;
        position: relative;
    }
    
    .order-card:hover {
        box-shadow: 0 8px 32px rgba(0,0,0,0.12);
        transform: translateY(-3px);
    }
    
    .order-status {
        position: absolute;
        top: 1rem;
        right: 1rem;
        padding: 0.3rem 0.8rem;
        border-radius: 12px;
        font-size: 0.8rem;
        font-weight: 600;
    }
    
    .order-status.pending {
        background: #fff3cd;
        color: #856404;
    }
    
    .order-status.completed {
        background: #d4edda;
        color: #155724;
    }
    
    .order-status.cancelled {
        background: #f8d7da;
        color: #721c24;
    }
    
    /* 推荐系统卡片 */
    .recommendation-card {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        border-radius: 16px;
        padding: 1.5rem;
        margin: 1rem 0;
        border-left: 5px solid #28a745;
        box-shadow: 0 4px 16px rgba(40, 167, 69, 0.15);
        position: relative;
    }
    
    /* 智能标签 */
    .ai-badge {
        background: linear-gradient(135deg, #6c63ff 0%, #4834d4 100%);
        color: white;
        padding: 0.3rem 0.8rem;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 600;
        display: inline-block;
        margin-bottom: 0.5rem;
    }
    
    /* 聊天界面 - 现代化设计 */
    .chat-container {
        background: white;
        border-radius: 20px;
        padding: 2rem;
        margin: 1.5rem 0;
        box-shadow: 0 8px 32px rgba(0,0,0,0.1);
        border: 1px solid #f0f2f5;
        position: relative;
    }
    
    .chat-container::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, #667eea, #764ba2);
        border-radius: 20px 20px 0 0;
    }
    
    /* 消息气泡优化 */
    .user-message {
        background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
        color: white;
        padding: 1rem 1.5rem;
        border-radius: 20px 20px 8px 20px;
        margin: 0.8rem 0;
        max-width: 75%;
        margin-left: auto;
        box-shadow: 0 4px 16px rgba(0, 123, 255, 0.3);
        position: relative;
    }
    
    .ai-message {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        color: #2c3e50;
        padding: 1rem 1.5rem;
        border-radius: 20px 20px 20px 8px;
        margin: 0.8rem 0;
        max-width: 75%;
        border: 1px solid #dee2e6;
        box-shadow: 0 4px 16px rgba(0,0,0,0.05);
    }
    
    /* 按钮系统优化 */
    .stButton > button {
        background: linear-gradient(135deg, #e3000b 0%, #ff6b35 100%);
        color: white;
        border: none;
        border-radius: 12px;
        padding: 0.8rem 1.5rem;
        font-weight: 600;
        font-size: 0.95rem;
        transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        box-shadow: 0 4px 16px rgba(227, 0, 11, 0.3);
        position: relative;
        overflow: hidden;
    }
    
    .stButton > button::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
        transition: left 0.5s;
    }
    
    .stButton > button:hover {
        background: linear-gradient(135deg, #c2000a 0%, #e55a2b 100%);
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(227, 0, 11, 0.4);
    }
    
    .stButton > button:hover::before {
        left: 100%;
    }
    
    /* 次要按钮 */
    .secondary-button {
        background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
        color: white;
        border: none;
        border-radius: 12px;
        padding: 0.8rem 1.5rem;
        font-weight: 600;
        transition: all 0.3s ease;
    }
    
    /* 输入框优化 */
    .stTextInput > div > div > input {
        border-radius: 12px;
        border: 2px solid #e9ecef;
        padding: 1rem;
        font-size: 0.95rem;
        transition: all 0.3s ease;
        background: #f8f9fa;
    }
    
    .stTextInput > div > div > input:focus {
        border-color: #e3000b;
        box-shadow: 0 0 0 4px rgba(227, 0, 11, 0.1);
        background: white;
    }
    
    /* 选择框优化 */
    .stSelectbox > div > div {
        border-radius: 12px;
        border: 2px solid #e9ecef;
        background: #f8f9fa;
    }
    
    .stSelectbox > div > div:focus-within {
        border-color: #e3000b;
        box-shadow: 0 0 0 4px rgba(227, 0, 11, 0.1);
    }
    
    /* 滑块优化 */
    .stSlider > div > div > div > div {
        background-color: #e3000b !important;
    }
    
    /* 数量控制器 */
    .quantity-control {
        display: flex;
        align-items: center;
        gap: 0.8rem;
        margin: 1rem 0;
        background: white;
        padding: 0.8rem;
        border-radius: 12px;
        border: 2px solid #e9ecef;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }
    
    /* 统计卡片 */
    .metric-card {
        background: white;
        border-radius: 16px;
        padding: 2rem;
        text-align: center;
        box-shadow: 0 4px 16px rgba(0,0,0,0.08);
        border: 1px solid #f0f2f5;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }
    
    .metric-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, #667eea, #764ba2);
    }
    
    .metric-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 32px rgba(0,0,0,0.12);
    }
    
    .metric-number {
        font-size: 2.2rem;
        font-weight: 700;
        color: #2c3e50;
        margin-bottom: 0.5rem;
    }
    
    .metric-label {
        font-size: 0.9rem;
        color: #7f8c8d;
        font-weight: 500;
    }
    
    /* 导航标签页 - 现代化设计 */
    .stTabs [data-baseweb="tab-list"] {
        gap: 0.5rem;
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        padding: 0.8rem;
        border-radius: 16px;
        margin-bottom: 1.5rem;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }
    
    .stTabs [data-baseweb="tab"] {
        background: white;
        border-radius: 12px;
        color: #495057;
        font-weight: 600;
        padding: 1rem 1.5rem;
        border: none;
        transition: all 0.3s ease;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    }
    
    .stTabs [data-baseweb="tab"]:hover {
        background: linear-gradient(135deg, #e3000b 0%, #ff6b35 100%);
        color: white;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(227, 0, 11, 0.3);
    }
    
    .stTabs [aria-selected="true"] {
        background: linear-gradient(135deg, #e3000b 0%, #ff6b35 100%) !important;
        color: white !important;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(227, 0, 11, 0.4);
    }
    
    /* 加载动画 */
    @keyframes float {
        0%, 100% { transform: translateY(0px) rotate(0deg); }
        50% { transform: translateY(-10px) rotate(180deg); }
    }
    
    @keyframes pulse {
        0%, 100% { opacity: 1; transform: scale(1); }
        50% { opacity: 0.8; transform: scale(1.05); }
    }
    
    @keyframes slideIn {
        from { transform: translateX(-100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    
    .loading {
        animation: pulse 2s infinite;
    }
    
    .slide-in {
        animation: slideIn 0.5s ease-out;
    }
    
    /* 成功/错误提示优化 */
    .stSuccess {
        background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
        border-left: 5px solid #28a745;
        border-radius: 12px;
        box-shadow: 0 4px 16px rgba(40, 167, 69, 0.2);
    }
    
    .stError {
        background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%);
        border-left: 5px solid #dc3545;
        border-radius: 12px;
        box-shadow: 0 4px 16px rgba(220, 53, 69, 0.2);
    }
    
    .stWarning {
        background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
        border-left: 5px solid #ffc107;
        border-radius: 12px;
        box-shadow: 0 4px 16px rgba(255, 193, 7, 0.2);
    }
    
    .stInfo {
        background: linear-gradient(135deg, #d1ecf1 0%, #b3d9e8 100%);
        border-left: 5px solid #17a2b8;
        border-radius: 12px;
        box-shadow: 0 4px 16px rgba(23, 162, 184, 0.2);
    }
    
    /* 搜索框特殊样式 */
    .search-box {
        background: white;
        border: 2px solid #e9ecef;
        border-radius: 25px;
        padding: 0.8rem 1.5rem;
        font-size: 0.95rem;
        transition: all 0.3s ease;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }
    
    .search-box:focus {
        border-color: #e3000b;
        box-shadow: 0 0 0 4px rgba(227, 0, 11, 0.1);
        outline: none;
    }
    
    /* 评分星星 */
    .rating-stars {
        color: #ffc107;
        font-size: 1.1rem;
        margin: 0.3rem 0;
    }
    
    /* 徽章样式 */
    .badge {
        display: inline-block;
        padding: 0.3rem 0.8rem;
        border-radius: 12px;
        font-size: 0.8rem;
        font-weight: 600;
    }
    
    .badge-primary {
        background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
        color: white;
    }
    
    .badge-success {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        color: white;
    }
    
    .badge-warning {
        background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
        color: #212529;
    }
    
    .badge-danger {
        background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
        color: white;
    }
    
    /* 响应式设计优化 */
    @media (max-width: 1200px) {
        .main .block-container {
            max-width: 95%;
            padding: 0.5rem 1rem;
        }
    }
    
    @media (max-width: 768px) {
        .main .block-container {
            padding: 0.5rem;
        }
        
        .product-card {
            padding: 1rem;
            min-height: 160px;
        }
        
        .user-info {
            padding: 1rem;
        }
        
        .chat-container {
            padding: 1rem;
        }
        
        .top-header {
            padding: 0.8rem 1rem;
        }
        
        .top-header h1 {
            font-size: 1.3rem;
        }
        
        .metric-card {
            padding: 1rem;
        }
        
        .stTabs [data-baseweb="tab"] {
            padding: 0.8rem 1rem;
            font-size: 0.9rem;
        }
    }
    
    @media (max-width: 480px) {
        .user-message, .ai-message {
            max-width: 90%;
            padding: 0.8rem 1rem;
        }
        
        .price-badge {
            font-size: 1rem;
            padding: 0.3rem 0.8rem;
        }
        
        .stButton > button {
            padding: 0.7rem 1rem;
            font-size: 0.9rem;
        }
    }
    
    /* 深色模式适配 */
    @media (prefers-color-scheme: dark) {
        .product-card {
            background: #2c3e50;
            border-color: #34495e;
            color: #ecf0f1;
        }
        
        .user-info {
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
        }
        
        .chat-container {
            background: #2c3e50;
            border-color: #34495e;
        }
    }
</style>
""", unsafe_allow_html=True)

# 数据加载函数
@st.cache_data
def load_users_data():
    """加载用户数据"""
    try:
        if USERS_FILE.exists():
            with open(USERS_FILE, 'r', encoding='utf-8') as f:
                data = json.load(f)
                # 确保数据结构正确
                if "users" in data:
                    return data
                else:
                    # 如果是简单格式，转换为标准格式
                    return {"users": data, "sessions": {}, "created_at": datetime.now().isoformat()}
        else:
            return {"users": {}, "sessions": {}, "created_at": datetime.now().isoformat()}
    except Exception as e:
        st.error(f"加载用户数据失败：{e}")
        return {"users": {}, "sessions": {}, "created_at": datetime.now().isoformat()}

@st.cache_data
def load_orders_data():
    """加载订单数据"""
    try:
        if ORDERS_FILE.exists():
            with open(ORDERS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        else:
            # 如果订单文件不存在，返回默认结构
            return {"orders": {}, "created_at": datetime.now().isoformat()}
    except Exception as e:
        st.error(f"加载订单数据失败：{e}")
        return {"orders": {}, "created_at": datetime.now().isoformat()}

def get_user_orders(email: str) -> List[Dict]:
    """获取用户订单"""
    orders_data = load_orders_data()
    orders_dict = orders_data.get("orders", {})
    
    # 直接通过邮箱地址获取订单列表
    user_orders = orders_dict.get(email, [])
    
    return sorted(user_orders, key=lambda x: x.get("created_at", ""), reverse=True)

def hash_password(password: str) -> str:
    """密码哈希"""
    return hashlib.sha256(password.encode()).hexdigest()

def authenticate_user(email: str, password: str) -> Optional[Dict]:
    """用户认证"""
    users_data = load_users_data()
    users = users_data.get("users", {})
    
    if email in users:
        user = users[email]
        if user.get("password") == hash_password(password):
            # 添加邮箱地址到用户对象中
            user["email"] = email
            return user
    return None

def get_recommendation_from_api(username: str) -> List[Dict]:
    """获取推荐商品（使用本地服务）"""
    try:
        recommendation_service = get_recommendation_service()
        return recommendation_service.get_recommendations(username)
    except Exception as e:
        st.error(f"获取推荐失败：{e}")
        return []

def get_career_report_from_api(user_email: str) -> Optional[Dict]:
    """直接调用生涯分析功能获取个人生涯报告"""
    try:
        # 直接使用本地生涯分析功能
        career_agent = get_career_agent()
        return career_agent.generate_career_report(user_email)
    except Exception as e:
        print(f"生成生涯报告失败：{e}")
        return None

def get_career_agent():
    """获取生涯分析代理实例"""
    if CAREER_ANALYSIS_AVAILABLE:
        return CareerOverviewAgent()
    else:
        return CareerOverviewAgent()  # 返回备用版本

class AdvancedRecommendationService:
    """增强的商品推荐服务 - 基于智能算法的推荐引擎"""
    
    def __init__(self):
        self.products = []
        self.users = {}
        self.recommendations_cache = {}
        self.load_env_config()
        self.load_local_data()
    
    def load_env_config(self):
        """加载环境配置"""
        try:
            from dotenv import load_dotenv
            # 加载项目根目录中的.env文件
            env_path = PROJECT_ROOT / ".env"
            if env_path.exists():
                load_dotenv(env_path)
                print(f"✅ 已加载环境配置: {env_path}")
            else:
                print("⚠️ 未找到.env文件，使用默认配置")
        except ImportError:
            print("⚠️ dotenv模块未安装，使用默认配置")
        except Exception as e:
            print(f"⚠️ 加载环境配置失败: {e}")
    
    def load_local_data(self):
        """加载本地商品和用户数据"""
        try:
            # 加载商品数据
            if GOODS_FILE.exists():
                with open(GOODS_FILE, 'r', encoding='utf-8') as f:
                    goods_data = json.load(f)
                    # 商品数据已经是标准格式
                    self.products = goods_data
            
            # 加载推荐用户数据
            if RECOMMENDATION_USERS_FILE.exists():
                with open(RECOMMENDATION_USERS_FILE, 'r', encoding='utf-8') as f:
                    users_data = json.load(f)
                    for user in users_data:
                        self.users[user["username"]] = user.get("purchased_product_ids", [])
        except Exception as e:
            st.warning(f"加载推荐数据失败：{e}")
            # 创建默认数据
            self.products = [
                {"id": 1, "name": "智能手机", "category": "electronics", "price": 2999, "tags": ["智能", "通讯"], "merchant": "科技商城"},
                {"id": 2, "name": "蓝牙耳机", "category": "electronics", "price": 299, "tags": ["音频", "蓝牙"], "merchant": "音响专卖"},
                {"id": 3, "name": "智能手表", "category": "electronics", "price": 1299, "tags": ["智能", "运动"], "merchant": "科技商城"},
                {"id": 4, "name": "笔记本电脑", "category": "electronics", "price": 5999, "tags": ["电脑", "办公"], "merchant": "电脑城"},
                {"id": 5, "name": "无线充电器", "category": "electronics", "price": 199, "tags": ["充电", "无线"], "merchant": "配件店"},
                {"id": 6, "name": "平板电脑", "category": "electronics", "price": 3499, "tags": ["平板", "娱乐"], "merchant": "科技商城"},
                {"id": 7, "name": "智能音响", "category": "electronics", "price": 699, "tags": ["音响", "智能"], "merchant": "音响专卖"},
                {"id": 8, "name": "无人机", "category": "electronics", "price": 4999, "tags": ["飞行", "摄影"], "merchant": "户外装备"},
                {"id": 9, "name": "游戏手柄", "category": "electronics", "price": 399, "tags": ["游戏", "控制"], "merchant": "游戏设备"},
                {"id": 10, "name": "移动电源", "category": "electronics", "price": 129, "tags": ["充电", "便携"], "merchant": "配件店"}
            ]
            self.users = {}
    
    def describe_user(self, username: str) -> str:
        """生成用户画像描述"""
        user_history = self.users.get(username, [])
        
        if not user_history:
            return "用户暂无购买记录"
        
        # 统计用户购买的商品类别和价格
        categories = []
        prices = []
        product_names = []
        
        for product_id in user_history:
            for product in self.products:
                if product["id"] == product_id:
                    categories.append(product["category"])
                    prices.append(product["price"])
                    product_names.append(product["name"])
                    break
        
        if not categories:
            return "用户购买记录无有效商品信息"
        
        # 分析用户偏好
        from collections import Counter
        category_counter = Counter(categories)
        most_liked_category = category_counter.most_common(1)[0][0]
        avg_price = sum(prices) / len(prices)
        
        return f"用户偏好'{most_liked_category}'类商品，平均消费¥{avg_price:.2f}，购买过{len(product_names)}件商品"
    
    def get_recommendations(self, username: str, top_k: int = 5) -> List[Dict]:
        """获取用户推荐商品（基于神经网络思路的加权推荐）"""
        # 检查缓存
        cache_key = f"{username}_{top_k}"
        if cache_key in self.recommendations_cache:
            cached_result = self.recommendations_cache[cache_key]
            # 简单的缓存过期策略（基于时间）
            if time.time() - cached_result["timestamp"] < 300:  # 5分钟缓存
                return cached_result["recommendations"]
        
        user_history = self.users.get(username, [])
        
        # 如果用户没有购买历史，返回热门商品
        if not user_history:
            return self._get_popular_products(top_k)
        
        # 基于神经网络思路的加权推荐算法
        from collections import defaultdict
        
        # 统计类别权重（类似神经元权重）
        category_weights = defaultdict(int)
        purchased_prices = []
        purchased_ids = set(user_history)
        
        for product_id in user_history:
            for product in self.products:
                if product["id"] == product_id:
                    category_weights[product["category"]] += 1
                    purchased_prices.append(product["price"])
                    break
        
        # 计算平均价格
        avg_price = sum(purchased_prices) / len(purchased_prices) if purchased_prices else 0
        total_purchases = sum(category_weights.values())
        
        # 计算每个未购买商品的推荐分数
        scored_products = []
        for product in self.products:
            if product["id"] in purchased_ids:
                continue
            
            # 类别权重分数 (70%)
            category_score = category_weights.get(product["category"], 0) / total_purchases if total_purchases > 0 else 0
            
            # 价格相似度分数 (30%)
            price_score = 0
            if avg_price > 0:
                price_diff = abs(product["price"] - avg_price) / avg_price
                price_score = max(0, 1 - price_diff)
            
            # 综合评分
            final_score = 0.7 * category_score + 0.3 * price_score
            scored_products.append((final_score, product))
        
        # 按分数排序并取前k个
        scored_products.sort(key=lambda x: x[0], reverse=True)
        recommendations = [product for _, product in scored_products[:top_k]]
        
        # 缓存结果
        self.recommendations_cache[cache_key] = {
            "recommendations": recommendations,
            "timestamp": time.time()
        }
        
        return recommendations
    
    def _get_popular_products(self, k: int) -> List[Dict]:
        """获取热门商品"""
        # 统计每个商品的购买次数
        from collections import defaultdict
        popularity_score = defaultdict(int)
        
        for user_purchases in self.users.values():
            for product_id in user_purchases:
                popularity_score[product_id] += 1
        
        # 按受欢迎程度排序
        popular_products = []
        for product in self.products:
            score = popularity_score.get(product["id"], 0)
            popular_products.append((score, product))
        
        popular_products.sort(key=lambda x: x[0], reverse=True)
        return [product for _, product in popular_products[:k]]
    
    def get_user_purchase_history(self, username: str) -> List[Dict]:
        """获取用户购买历史详情"""
        user_history = self.users.get(username, [])
        history_details = []
        
        for product_id in user_history:
            for product in self.products:
                if product["id"] == product_id:
                    history_details.append(product)
                    break
        
        return history_details
    
    def save_recommendation_data(self):
        """保存推荐数据到文件"""
        try:
            # 保存用户购买数据
            users_data = []
            for username, purchased_ids in self.users.items():
                users_data.append({
                    "username": username,
                    "purchased_product_ids": purchased_ids
                })
            
            with open(PROJECT_ROOT / "data" / "recommendation_users.json", 'w', encoding='utf-8') as f:
                json.dump(users_data, f, ensure_ascii=False, indent=2)
            
            return True
        except Exception as e:
            print(f"保存推荐数据失败：{e}")
            return False
    
    def simulate_purchase(self, username: str, product_id: int) -> bool:
        """模拟购买商品"""
        try:
            if username not in self.users:
                self.users[username] = []
            
            if product_id not in self.users[username]:
                self.users[username].append(product_id)
                # 清除相关缓存
                keys_to_remove = [key for key in self.recommendations_cache.keys() if key.startswith(f"{username}_")]
                for key in keys_to_remove:
                    del self.recommendations_cache[key]
                
                # 保存数据到文件
                self.save_recommendation_data()
            
            return True
        except Exception:
            return False
    
    def get_health_status(self) -> Dict:
        """获取服务健康状态"""
        return {
            "status": "healthy",
            "users_count": len(self.users),
            "products_count": len(self.products),
            "cache_size": len(self.recommendations_cache)
        }

# 创建全局推荐服务实例
@st.cache_resource
def get_recommendation_service():
    """获取推荐服务实例"""
    return AdvancedRecommendationService()

def get_user_purchase_history(username: str) -> List[Dict]:
    """获取用户购买历史（使用本地服务）"""
    try:
        recommendation_service = get_recommendation_service()
        return recommendation_service.get_user_purchase_history(username)
    except Exception as e:
        st.error(f"获取购买历史失败：{e}")
        return []

def simulate_purchase(username: str, product_id: int) -> bool:
    """模拟购买（使用本地服务）"""
    try:
        recommendation_service = get_recommendation_service()
        return recommendation_service.simulate_purchase(username, product_id)
    except Exception as e:
        st.error(f"购买失败：{e}")
        return False

def process_purchase(username: str, product_id: int, quantity: int = 1, user_email: str = None, coupon_id: str = None) -> Dict:
    """处理商品购买，创建订单并更新购买记录"""
    try:
        # 获取商品信息
        recommendation_service = get_recommendation_service()
        product = None
        for p in recommendation_service.products:
            if p["id"] == product_id:
                product = p
                break
        
        if not product:
            return {"success": False, "message": "商品不存在"}
        
        # 计算原始总价
        original_amount = product["price"] * quantity
        
        # 应用会员折扣
        discount_info = apply_membership_discount(username, original_amount)
        final_amount = discount_info["final_amount"]
        
        # 应用优惠券
        coupon_discount = 0
        shipping_free = False
        coupon_info = {}
        
        if coupon_id:
            try:
                from utils.coupon_system import use_coupon
                coupon_result = use_coupon(user_email or f"{username}@example.com", coupon_id, final_amount)
                if coupon_result["success"]:
                    coupon_info = coupon_result["coupon"]
                    if coupon_info["type"] == "coupon":
                        coupon_discount = coupon_result["discount_amount"]
                        final_amount -= coupon_discount
                    elif coupon_info["type"] == "free_shipping":
                        shipping_free = True
            except ImportError:
                pass  # 优惠券系统不可用
        
        # 生成订单ID
        order_id = f"ORD_{datetime.now().strftime('%Y%m%d%H%M%S')}_{uuid.uuid4().hex[:8].upper()}"
        
        # 创建订单
        order = {
            "order_id": order_id,
            "user_email": user_email or f"{username}@example.com",
            "status": "pending",
            "total_amount": final_amount,
            "original_amount": original_amount,
            "membership_discount": discount_info.get("discount_amount", 0),
            "coupon_discount": coupon_discount,
            "shipping_free": shipping_free,
            "coupon_id": coupon_id,
            "created_at": datetime.now().isoformat(),
            "items": [{
                "product_id": product_id,
                "name": product["name"],
                "price": product["price"],
                "quantity": quantity,
                "category": product.get("category", ""),
                "merchant": product.get("merchant", "")
            }],
            "shipping_address": "默认地址",
            "phone": "未设置",
            "payment_method": "online"
        }
        
        # 保存订单到文件
        orders_data = load_orders_data()
        if user_email not in orders_data.get("orders", {}):
            orders_data["orders"][user_email] = []
        orders_data["orders"][user_email].append(order)
        
        # 保存订单数据
        try:
            with open(ORDERS_FILE, 'w', encoding='utf-8') as f:
                json.dump(orders_data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            return {"success": False, "message": f"保存订单失败: {e}"}
        
        # 更新推荐系统的购买记录
        recommendation_service.simulate_purchase(username, product_id)
        
        # 添加购物积分
        if POINTS_SYSTEM_AVAILABLE:
            points_result = add_purchase_points(user_email, order_id, final_amount)
            
            # 更新会员信息
            update_membership_after_purchase(username, final_amount)
            
            if points_result["success"]:
                message = f"购买成功! 获得{points_result['points']}积分"
                if discount_info.get("membership_applied"):
                    message += f"，享受{discount_info.get('level_name', '会员')}优惠¥{discount_info.get('discount_amount', 0):.2f}"
                if coupon_discount > 0:
                    message += f"，优惠券优惠¥{coupon_discount:.2f}"
                if shipping_free:
                    message += f"，免运费"
                
                return {
                    "success": True, 
                    "message": message,
                    "order_id": order_id,
                    "total_amount": final_amount,
                    "original_amount": original_amount,
                    "membership_discount": discount_info.get("discount_amount", 0),
                    "coupon_discount": coupon_discount,
                    "shipping_free": shipping_free,
                    "points_earned": points_result['points']
                }
        
        # 如果积分系统不可用，仍然更新会员信息
        update_membership_after_purchase(username, final_amount)
        
        message = "购买成功"
        if discount_info.get("membership_applied"):
            message += f"，享受{discount_info.get('level_name', '会员')}优惠¥{discount_info.get('discount_amount', 0):.2f}"
        if coupon_discount > 0:
            message += f"，优惠券优惠¥{coupon_discount:.2f}"
        if shipping_free:
            message += f"，免运费"
        
        return {
            "success": True, 
            "message": message,
            "order_id": order_id,
            "total_amount": final_amount,
            "original_amount": original_amount,
            "membership_discount": discount_info.get("discount_amount", 0),
            "coupon_discount": coupon_discount,
            "shipping_free": shipping_free
        }
        
    except Exception as e:
        return {"success": False, "message": f"购买失败: {str(e)}"}

def get_cart_items(user_email: str) -> List[Dict]:
    """获取用户购物车商品"""
    # 这里简化实现，实际应该有独立的购物车存储
    if 'cart_items' not in st.session_state:
        st.session_state.cart_items = []
    return st.session_state.cart_items

def add_to_cart(product_id: int, quantity: int = 1) -> bool:
    """添加商品到购物车"""
    try:
        # 获取商品信息
        recommendation_service = get_recommendation_service()
        product = None
        for p in recommendation_service.products:
            if p["id"] == product_id:
                product = p
                break
        
        if not product:
            return False
        
        # 初始化购物车
        if 'cart_items' not in st.session_state:
            st.session_state.cart_items = []
        
        # 检查是否已存在该商品
        for item in st.session_state.cart_items:
            if item["product_id"] == product_id:
                item["quantity"] += quantity
                return True
        
        # 添加新商品
        cart_item = {
            "product_id": product_id,
            "name": product["name"],
            "price": product["price"],
            "quantity": quantity,
            "category": product.get("category", ""),
            "merchant": product.get("merchant", ""),
            "tags": product.get("tags", [])
        }
        st.session_state.cart_items.append(cart_item)
        return True
        
    except Exception as e:
        print(f"添加到购物车失败: {e}")
        return False

def remove_from_cart(product_id: int) -> bool:
    """从购物车移除商品"""
    try:
        if 'cart_items' not in st.session_state:
            return False
        
        st.session_state.cart_items = [
            item for item in st.session_state.cart_items 
            if item["product_id"] != product_id
        ]
        return True
        
    except Exception as e:
        print(f"从购物车移除失败: {e}")
        return False

def update_cart_quantity(product_id: int, quantity: int) -> bool:
    """更新购物车商品数量"""
    try:
        if 'cart_items' not in st.session_state:
            return False
        
        for item in st.session_state.cart_items:
            if item["product_id"] == product_id:
                if quantity <= 0:
                    return remove_from_cart(product_id)
                item["quantity"] = quantity
                return True
        return False
        
    except Exception as e:
        print(f"更新购物车数量失败: {e}")
        return False

def clear_cart():
    """清空购物车"""
    if 'cart_items' in st.session_state:
        st.session_state.cart_items = []

def get_total_orders_count() -> int:
    """获取订单总数"""
    orders_data = load_orders_data()
    total_count = 0
    
    orders_dict = orders_data.get("orders", {})
    for email, orders in orders_dict.items():
        if isinstance(orders, list):
            total_count += len(orders)
    
    return total_count

def get_purchase_statistics(user_email: str) -> Dict:
    """获取用户购买统计"""
    try:
        orders = get_user_orders(user_email)
        total_orders = len(orders)
        total_amount = sum(order.get("total_amount", 0) for order in orders)
        
        # 统计商品类别
        categories = {}
        for order in orders:
            items = order.get("items", [])
            for item in items:
                if isinstance(item, dict):
                    category = item.get("category", "未知")
                    categories[category] = categories.get(category, 0) + item.get("quantity", 1)
        
        return {
            "total_orders": total_orders,
            "total_amount": total_amount,
            "categories": categories,
            "avg_order_amount": total_amount / total_orders if total_orders > 0 else 0
        }
    except Exception as e:
        print(f"获取购买统计失败: {e}")
        return {"total_orders": 0, "total_amount": 0, "categories": {}, "avg_order_amount": 0}

# 初始化session state
if 'user' not in st.session_state:
    st.session_state.user = None
if 'current_page' not in st.session_state:
    st.session_state.current_page = 'login'
if 'chat_history' not in st.session_state:
    st.session_state.chat_history = []
if 'cart_items' not in st.session_state:
    st.session_state.cart_items = []
if 'show_checkout' not in st.session_state:
    st.session_state.show_checkout = False

# 初始化AI助手
def init_ai_assistant():
    """初始化AI助手"""
    if 'ai_assistant' not in st.session_state:
        try:
            # 优先使用硅基流动AI助手（用于对话）
            if AI_ASSISTANT_AVAILABLE:
                api_key = os.environ.get("SILICONFLOW_API_KEY")
                if api_key and api_key.startswith("sk-"):
                    # 初始化云端AI助手
                    with st.spinner("正在初始化硅基流动AI助手..."):
                        st.session_state.ai_assistant = SmartAssistant()
                        st.session_state.customer_service_session = None
                        st.success("✅ 硅基流动AI智能客服已启用")
                        print("✅ 使用硅基流动DeepSeek AI助手")
                        return
            
            # 备用：使用本地Ollama助手
            local_assistant = LocalOllamaAssistant()
            if local_assistant.available:
                st.session_state.ai_assistant = local_assistant
                st.session_state.customer_service_session = None
                st.info("✅ 本地Ollama AI客服已启用（备用）")
                print("✅ 使用本地Ollama AI助手（备用）")
                return
            
            # 都不可用时使用基础客服
            st.session_state.ai_assistant = None
            st.warning("⚠️ AI助手服务暂不可用，将使用基础客服服务")
            print("⚠️ 使用基础客服服务")
                
        except Exception as e:
            error_msg = f"AI助手初始化失败: {str(e)}"
            print(error_msg)
            st.warning(f"⚠️ {error_msg}，将使用基础客服服务")
            st.session_state.ai_assistant = None
    
    # 如果AI助手模块完全不可用
    if not AI_ASSISTANT_AVAILABLE and 'ai_assistant' not in st.session_state:
        st.session_state.ai_assistant = None
        st.info("📝 AI助手模块未完全加载，使用基础客服服务")

# 初始化AI助手（只在首次加载时进行）
if 'ai_assistant_initialized' not in st.session_state:
    st.session_state.ai_assistant_initialized = True
    init_ai_assistant()

def preprocess_text(text):
    """中文文本预处理"""
    # 中文分词
    text = " ".join(jieba.cut(text))
    # 保留字母数字和中文
    text = ''.join([c if c.isalnum() or '\u4e00' <= c <= '\u9fff' else ' ' for c in text])
    return text.lower().strip()

# 搜索商品
def search_products(query: str, top_k: int = 10, min_score: float = 0.15) -> List[Dict]:
    products = get_recommendation_service().products
    if not products or not query.strip():
        return []

    # 预处理查询词
    processed_query = preprocess_text(query)

    # 构建商品搜索文本（增强版）
    product_texts = []
    for product in products:
        # 组合多个字段（名称3次，分类2次，标签2次，商家1次）
        text_parts = [
            product.get('name', '') * 3,  # 名称权重最高
            product.get('category', '') * 2,
            ' '.join(product.get('tags', [])) * 2,
            product.get('merchant', ''),
            product.get('description', '')
        ]
        full_text = " ".join(text_parts)
        product_texts.append(preprocess_text(full_text))

    # 优化TF-IDF参数
    vectorizer = TfidfVectorizer(
        analyzer='word',
        token_pattern=r'(?u)\b\w+\b',
        ngram_range=(1, 2),  # 同时匹配单个词和词组
        min_df=1,  # 最小出现次数设为1
        max_df=0.9,  # 忽略出现在90%以上文档中的词
        use_idf=True,
        smooth_idf=True
    )

    try:
        # 向量化
        tfidf_matrix = vectorizer.fit_transform(product_texts)
        query_vec = vectorizer.transform([processed_query])

        # 计算相似度（使用更宽松的余弦相似度）
        cosine_sim = cosine_similarity(query_vec, tfidf_matrix).flatten()

        # 获取所有匹配商品（不再严格限制阈值）
        matched_indices = cosine_sim.argsort()[::-1]  # 降序排列
        matched_products = [(products[i], cosine_sim[i])
                            for i in matched_indices
                            if cosine_sim[i] > 0]  # 只要相似度>0就保留

        # 返回top_k个结果
        return [p for p, _ in matched_products[:top_k]]

    except Exception as e:
        print(f"搜索出错: {str(e)}")
        return []

# 主应用
def main():
    # 初始化推荐服务（如果还没有）
    if 'recommendation_service' not in st.session_state:
        st.session_state.recommendation_service = AdvancedRecommendationService()
    
    # 如果用户未登录，显示登录页面
    if st.session_state.user is None:
        show_login_page()
    else:
        show_main_app()

def show_login_page():
    """显示登录页面 - 现代化电商风格"""
    # 顶部品牌横幅
    st.markdown(f"""
    <div class="top-header">
        <div style="display: flex; justify-content: space-between; align-items: center;">
            <div>
                <h1>🛒 智能电商平台 {VERSION}</h1>
                <p class="subtitle">一站式购物体验，智能推荐，贴心服务</p>
            </div>
            <div style="text-align: right; opacity: 0.8;">
                <p style="margin: 0; font-size: 0.8rem;">体验版本</p>
                <p style="margin: 0; font-size: 0.8rem;">安全 · 快速 · 智能</p>
            </div>
        </div>
    </div>
    """, unsafe_allow_html=True)
    
    # 主要内容区域
    col1, col2, col3 = st.columns([1, 3, 1])
    
    with col2:
        # 登录卡片
        st.markdown("""
        <div style="background: white; padding: 2.5rem; border-radius: 20px; 
                    box-shadow: 0 8px 32px rgba(0,0,0,0.1); margin: 2rem 0; border: 1px solid #f0f0f0;">
            <div style="text-align: center; margin-bottom: 2rem;">
                <h2 style="color: #333; margin: 0 0 0.5rem 0; font-weight: 700;">🔐 账户登录</h2>
                <p style="color: #666; margin: 0; font-size: 0.95rem;">请输入您的账户信息</p>
            </div>
        """, unsafe_allow_html=True)
        
        with st.form("login_form", clear_on_submit=False):
            # 邮箱输入
            st.markdown('<div style="margin-bottom: 1rem;">', unsafe_allow_html=True)
            email = st.text_input("邮箱地址", placeholder="📧 请输入您的邮箱地址", key="login_email", label_visibility="collapsed")
            st.markdown('</div>', unsafe_allow_html=True)
            
            # 密码输入
            st.markdown('<div style="margin-bottom: 2rem;">', unsafe_allow_html=True)
            password = st.text_input("密码", type="password", placeholder="🔒 请输入您的密码", key="login_password", label_visibility="collapsed")
            st.markdown('</div>', unsafe_allow_html=True)
            
            # 登录按钮
            login_button = st.form_submit_button("🚀 立即登录", use_container_width=True)
            
            # 处理登录逻辑
            if login_button:
                if email and password:
                    user = authenticate_user(email, password)
                    if user:
                        st.session_state.user = user
                        st.session_state.current_page = 'main'
                        st.success("✅ 登录成功！")
                        st.rerun()
                    else:
                        st.error("❌ 邮箱或密码错误，请重试")
                else:
                    st.error("❌ 请填写完整的登录信息")
        
        # 快速登录选项
        st.markdown("---")
        st.markdown("#### 💡 快速登录")
        st.markdown("使用以下测试账户快速体验：")
        
        col1, col2 = st.columns(2)
        with col1:
            if st.button("👨‍💼 管理员登录", use_container_width=True):
                admin_user = {
                    "username": "admin",
                    "email": "admin@company.com",
                    "password": "admin123",
                    "role": "admin",
                    "profile": {
                        "nickname": "系统管理员",
                        "avatar": "👨‍💼",
                        "gender": "男",
                        "birthday": "1985-01-01",
                        "address": "总部办公室"
                    },
                    "preferences": {
                        "notification": True,
                        "marketing": False,
                        "theme": "default"
                    },
                    "created_at": "2024-01-01 00:00:00",
                    "last_login": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    "phone": "13800138000"
                }
                st.session_state.user = admin_user
                st.session_state.current_page = 'main'
                st.success("✅ 管理员登录成功！")
                st.rerun()
        
        with col2:
            if st.button("👤 普通用户登录", use_container_width=True):
                demo_user = {
                    "username": "demo",
                    "email": "demo@example.com",
                    "password": "demo123",
                    "role": "user",
                    "profile": {
                        "nickname": "演示用户",
                        "avatar": "👤",
                        "gender": "保密",
                        "birthday": "1990-01-01",
                        "address": "演示地址"
                    },
                    "preferences": {
                        "notification": True,
                        "marketing": True,
                        "theme": "default"
                    },
                    "created_at": "2024-01-01 00:00:00",
                    "last_login": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    "phone": "13912345678"
                }
                st.session_state.user = demo_user
                st.session_state.current_page = 'main'
                st.success("✅ 演示用户登录成功！")
                st.rerun()

def show_main_app():
    """显示主应用界面 - 现代化电商布局"""
    user = st.session_state.user
    
    # 顶部导航栏
    st.markdown(f"""
    <div class="top-header">
        <div style="display: flex; justify-content: space-between; align-items: center;">
            <div style="display: flex; align-items: center; gap: 1rem;">
                <h1 style="margin: 0; font-size: 1.3rem;">� 智能电商平台</h1>
                <span style="background: rgba(255,255,255,0.2); padding: 0.2rem 0.5rem; border-radius: 12px; font-size: 0.7rem;">
                    {VERSION}
                </span>
            </div>
            <div style="display: flex; align-items: center; gap: 1rem; font-size: 0.85rem;">
                <span>👤 {user.get('profile', {}).get('nickname', user.get('username', '用户'))}</span>
                <span>📧 {user.get('email', '')}</span>
            </div>
        </div>
    </div>
    """, unsafe_allow_html=True)
    
    # 用户状态栏
    col1, col2, col3, col4 = st.columns([3, 2, 2, 1.5])
    
    with col1:
        # 用户信息卡片
        st.markdown(f"""
        <div class="user-info">
            <div style="display: flex; align-items: center; gap: 1rem;">
                <div style="font-size: 2.5rem;">{user.get('profile', {}).get('avatar', '👤')}</div>
                <div>
                    <h3 style="margin: 0; font-size: 1.1rem;">
                        欢迎回来，{user.get('profile', {}).get('nickname', user.get('username', '用户'))}！
                    </h3>
                    <div style="display: flex; gap: 1rem; margin-top: 0.5rem; font-size: 0.8rem; opacity: 0.9;">
                        <span>📱 {user.get('phone', '未设置')}</span>
                        <span>🕒 {user.get('last_login', '首次登录')}</span>
                    </div>
                </div>
            </div>
        </div>
        """, unsafe_allow_html=True)
    
    with col2:
        # 购物车状态
        cart_items = get_cart_items(user.get('email', ''))
        cart_count = sum(item['quantity'] for item in cart_items)
        cart_total = sum(item['price'] * item['quantity'] for item in cart_items)
        
        if cart_count > 0:
            st.markdown(f"""
            <div class="status-card-secondary">
                <div style="font-size: 1.5rem; margin-bottom: 0.3rem;">🛒</div>
                <div style="font-weight: 600;">购物车: {cart_count} 件</div>
                <div style="font-size: 0.85rem; opacity: 0.9;">总计: ¥{cart_total:.2f}</div>
            </div>
            """, unsafe_allow_html=True)
        else:
            st.markdown("""
            <div style="background: #6c757d; color: white; padding: 1rem; border-radius: 10px; text-align: center;">
                <div style="font-size: 1.5rem; margin-bottom: 0.3rem;">�</div>
                <div style="font-weight: 600;">购物车空</div>
                <div style="font-size: 0.85rem; opacity: 0.9;">去逛逛吧</div>
            </div>
            """, unsafe_allow_html=True)
    
    with col3:
        # 积分状态
        if POINTS_SYSTEM_AVAILABLE:
            user_points = get_user_points(user.get('email', ''))
            st.markdown(f"""
            <div class="status-card-points">
                <div style="font-size: 1.5rem; margin-bottom: 0.3rem;">🎯</div>
                <div style="font-weight: 600;">我的积分</div>
                <div style="font-size: 1.1rem; font-weight: 700;">{user_points}</div>
            </div>
            """, unsafe_allow_html=True)
        else:
            st.markdown("""
            <div style="background: #dc3545; color: white; padding: 1rem; border-radius: 10px; text-align: center;">
                <div style="font-size: 1.5rem; margin-bottom: 0.3rem;">🎯</div>
                <div style="font-weight: 600;">积分系统</div>
                <div style="font-size: 0.85rem; opacity: 0.9;">暂不可用</div>
            </div>
            """, unsafe_allow_html=True)
    
    with col4:
        # 退出登录按钮
        if st.button("🚪 退出", use_container_width=True):
            st.session_state.user = None
            st.session_state.current_page = 'login'
            st.session_state.chat_history = []
            st.session_state.cart_items = []
            st.session_state.show_checkout = False
            st.rerun()
    
    # 分隔线
    st.markdown("<hr style='margin: 1.5rem 0; border: none; height: 1px; background: linear-gradient(90deg, transparent, #e9ecef, transparent);'>", unsafe_allow_html=True)
def show_main_app():
    """显示主应用界面"""
    user = st.session_state.user
    
    # 显示会员升级通知
    if MEMBERSHIP_AVAILABLE:
        show_membership_upgrade_notification()
    
    # 头部信息
    col1, col2, col3 = st.columns([2, 1, 1])
    
    with col1:
        st.markdown(f"""
        <div class="user-info">
            <h3>{user.get('profile', {}).get('avatar', '👤')} 欢迎，{user.get('profile', {}).get('nickname', user.get('username', '用户'))}</h3>
            <p>📧 {user.get('email', '')} | 📱 {user.get('phone', '')} | 🕒 上次登录：{user.get('last_login', '')} | 📦 {VERSION}</p>
        </div>
        """, unsafe_allow_html=True)
    
    with col2:
        # 购物车状态
        cart_items = get_cart_items(user.get('email', ''))
        cart_count = sum(item['quantity'] for item in cart_items)
        cart_total = sum(item['price'] * item['quantity'] for item in cart_items)
        
        # 积分显示
        if POINTS_SYSTEM_AVAILABLE:
            user_points = get_user_points(user.get('email', ''))
            if cart_count > 0:
                st.markdown(f"""
                <div style="background: #28a745; color: white; padding: 0.5rem; border-radius: 8px; text-align: center; margin-bottom: 0.3rem;">
                    <strong>🛒 购物车: {cart_count} 件</strong><br>
                    <small>总计: ¥{cart_total:.2f}</small>
                </div>
                <div style="background: #ffc107; color: black; padding: 0.3rem; border-radius: 5px; text-align: center;">
                    <strong>🎯 积分: {user_points}</strong>
                </div>
                """, unsafe_allow_html=True)
            else:
                st.markdown(f"""
                <div style="background: #6c757d; color: white; padding: 0.5rem; border-radius: 8px; text-align: center; margin-bottom: 0.3rem;">
                    <strong>🛒 购物车空</strong>
                </div>
                <div style="background: #ffc107; color: black; padding: 0.3rem; border-radius: 5px; text-align: center;">
                    <strong>🎯 积分: {user_points}</strong>
                </div>
                """, unsafe_allow_html=True)
        else:
            if cart_count > 0:
                st.markdown(f"""
                <div style="background: #28a745; color: white; padding: 0.5rem; border-radius: 8px; text-align: center;">
                    <strong>🛒 购物车: {cart_count} 件</strong><br>
                    <small>总计: ¥{cart_total:.2f}</small>
                </div>
                """, unsafe_allow_html=True)
            else:
                st.markdown("""
                <div style="background: #6c757d; color: white; padding: 0.5rem; border-radius: 8px; text-align: center;">
                    <strong>🛒 购物车空</strong>
                </div>
                """, unsafe_allow_html=True)
    
    with col3:
        if st.button("🚪 退出登录", use_container_width=True):
            st.session_state.user = None
            st.session_state.current_page = 'login'
            st.session_state.chat_history = []
            st.session_state.cart_items = []
            st.session_state.show_checkout = False
            st.rerun()
    
    # 导航选项卡
    tabs = st.tabs(["🏠 概览", "🛒 商品购买", "🛍️ 商品推荐", "💬 客服助手", "👤 个人中心", "📦 订单管理", "🎯 积分中心", "💎 会员中心"])
    
    with tabs[0]:  # 概览
        show_dashboard()
    
    with tabs[1]:  # 商品购买
        show_shopping_page()
    
    with tabs[2]:  # 商品推荐
        show_recommendation_page()
    
    with tabs[3]:  # 客服助手
        show_chat_page()
    
    with tabs[4]:  # 个人中心
        show_profile_page()
    
    with tabs[5]:  # 订单管理
        show_orders_page()
    
    with tabs[6]:  # 积分中心
        show_points_page()
    
    with tabs[7]:  # 会员中心
        show_membership_page()

def show_dashboard():
    """显示概览页面 - 电商风格仪表板"""
    # 页面标题
    st.markdown("""
    <div style="text-align: center; margin-bottom: 2rem;">
        <h2 style="color: #333; margin: 0; font-weight: 700;">🏠 我的购物中心</h2>
        <p style="color: #666; margin: 0.5rem 0 0 0; font-size: 0.95rem;">您的专属购物概览</p>
    </div>
    """, unsafe_allow_html=True)
    
    # 核心数据统计卡片
    user_email = st.session_state.user.get("email", "")
    user_orders = get_user_orders(user_email)
    username = st.session_state.user.get("username", "")
    
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.markdown(f"""
        <div class="metric-card">
            <div style="font-size: 2.5rem; margin-bottom: 0.5rem; color: #e3000b;">📦</div>
            <h3 style="margin: 0; font-size: 1.8rem; font-weight: 700; color: #333;">{len(user_orders)}</h3>
            <p style="margin: 0.3rem 0 0 0; color: #666; font-size: 0.9rem;">我的订单</p>
        </div>
        """, unsafe_allow_html=True)
    
    with col2:
        total_users = len(load_users_data().get("users", {}))
        st.markdown(f"""
        <div class="metric-card">
            <div style="font-size: 2.5rem; margin-bottom: 0.5rem; color: #28a745;">👥</div>
            <h3 style="margin: 0; font-size: 1.8rem; font-weight: 700; color: #333;">{total_users}</h3>
            <p style="margin: 0.3rem 0 0 0; color: #666; font-size: 0.9rem;">平台用户</p>
        </div>
        """, unsafe_allow_html=True)
    
    with col3:
        total_orders = get_total_orders_count()
        st.markdown(f"""
        <div class="metric-card">
            <div style="font-size: 2.5rem; margin-bottom: 0.5rem; color: #17a2b8;">📊</div>
            <h3 style="margin: 0; font-size: 1.8rem; font-weight: 700; color: #333;">{total_orders}</h3>
            <p style="margin: 0.3rem 0 0 0; color: #666; font-size: 0.9rem;">总订单数</p>
        </div>
        """, unsafe_allow_html=True)
    
    with col4:
        if POINTS_SYSTEM_AVAILABLE:
            user_points = get_user_points(user_email)
            st.markdown(f"""
            <div class="metric-card">
                <div style="font-size: 2.5rem; margin-bottom: 0.5rem; color: #ffc107;">🎯</div>
                <h3 style="margin: 0; font-size: 1.8rem; font-weight: 700; color: #333;">{user_points}</h3>
                <p style="margin: 0.3rem 0 0 0; color: #666; font-size: 0.9rem;">我的积分</p>
            </div>
            """, unsafe_allow_html=True)
        else:
            st.markdown("""
            <div class="metric-card">
                <div style="font-size: 2.5rem; margin-bottom: 0.5rem; color: #dc3545;">❌</div>
                <h3 style="margin: 0; font-size: 1rem; font-weight: 600; color: #dc3545;">不可用</h3>
                <p style="margin: 0.3rem 0 0 0; color: #666; font-size: 0.9rem;">积分系统</p>
            </div>
            """, unsafe_allow_html=True)
    
    # 主要内容区域
    st.markdown("<div style='margin: 2rem 0;'></div>", unsafe_allow_html=True)
    
    # AI 个性报告区域 - 完整行
    st.markdown("""
    <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                padding: 2rem; border-radius: 20px; margin-bottom: 2rem; 
                box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3); color: white;">
        <div style="text-align: center; margin-bottom: 1.5rem;">
            <h3 style="margin: 0; color: white; font-weight: 700; font-size: 1.5rem;">
                🤖 AI 个性化生涯报告
            </h3>
            <p style="margin: 0.5rem 0 0 0; opacity: 0.9; font-size: 1rem;">
                基于您的购物行为、成长轨迹和消费偏好，AI 为您生成专属的个性化分析报告
            </p>
        </div>
    </div>
    """, unsafe_allow_html=True)
    
    # 生成报告按钮和显示区域
    col_btn, col_status = st.columns([2, 3])
    
    with col_btn:
        if st.button("🚀 AI 生成我的个性报告", use_container_width=True, key="ai_generate_report"):
            with st.spinner("🔍 AI 正在深度分析您的数据..."):
                try:
                    # 直接调用本地AI生涯分析功能
                    career_report = get_career_report_from_api(user_email)
                    
                    if career_report and "error" not in career_report:
                        st.session_state.ai_career_report = career_report
                        st.success("✅ AI 报告生成完成！")
                        st.balloons()
                        time.sleep(1)
                        st.rerun()
                    else:
                        error_msg = career_report.get("error", "未知错误") if career_report else "生成失败"
                        st.error(f"❌ 生成报告失败：{error_msg}")
                except Exception as e:
                    st.error(f"❌ AI 服务异常：{str(e)}")
    
    with col_status:
        if 'ai_career_report' in st.session_state and st.session_state.ai_career_report:
            st.markdown("""
            <div style="background: rgba(255,255,255,0.1); padding: 1rem; border-radius: 10px; 
                        border: 1px solid rgba(255,255,255,0.2);">
                <p style="margin: 0; color: #4CAF50; font-weight: 600;">
                    ✅ 最新报告已生成
                </p>
                <small style="color: rgba(255,255,255,0.8);">
                    生成时间：{datetime.now().strftime('%Y-%m-%d %H:%M')}
                </small>
            </div>
            """, unsafe_allow_html=True)
        else:
            st.markdown("""
            <div style="background: rgba(255,255,255,0.1); padding: 1rem; border-radius: 10px; 
                        border: 1px solid rgba(255,255,255,0.2);">
                <p style="margin: 0; color: rgba(255,255,255,0.7);">
                    📝 点击生成您的专属 AI 报告
                </p>
            </div>
            """, unsafe_allow_html=True)
    
    # 显示AI生涯报告详细内容（如果已生成）
    if 'ai_career_report' in st.session_state and st.session_state.ai_career_report:
        report = st.session_state.ai_career_report
        
        st.markdown("""
        <div style="background: white; padding: 2rem; border-radius: 20px; 
                    box-shadow: 0 8px 32px rgba(0,0,0,0.1); margin-bottom: 2rem; 
                    border: 1px solid #f0f0f0;">
            <div style="text-align: center; margin-bottom: 2rem;">
                <h4 style="margin: 0; color: #333; font-weight: 700; font-size: 1.3rem;">
                    📊 您的 AI 个性化分析报告
                </h4>
            </div>
        """, unsafe_allow_html=True)
        
        # 报告摘要卡片
        col_summary, col_score = st.columns([2, 1])
        
        with col_summary:
            st.markdown(f"""
            <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                        padding: 1.5rem; border-radius: 15px; color: white; margin-bottom: 1rem;">
                <h5 style="margin: 0 0 0.5rem 0; font-weight: 600;">🎯 AI 用户画像</h5>
                <p style="margin: 0; font-size: 1.1rem; font-weight: 500;">
                    {report.get('report_summary', '积极成长型用户')}
                </p>
            </div>
            """, unsafe_allow_html=True)
        
        with col_score:
            career_score = report.get('career_score', 0)
            score_color = "#4CAF50" if career_score >= 80 else "#FF9800" if career_score >= 60 else "#f44336"
            st.markdown(f"""
            <div style="background: {score_color}; padding: 1.5rem; border-radius: 15px; 
                        color: white; text-align: center; margin-bottom: 1rem;">
                <h5 style="margin: 0 0 0.5rem 0; font-weight: 600;">⭐ AI 评分</h5>
                <h2 style="margin: 0; font-size: 2.5rem; font-weight: 700;">{career_score}</h2>
                <small style="opacity: 0.9;">满分 100</small>
            </div>
            """, unsafe_allow_html=True)
        
        # 详细分析 - 三列布局
        col1, col2, col3 = st.columns(3)
        
        with col1:
            shopping_behavior = report.get('shopping_behavior', {})
            st.markdown(f"""
            <div style="background: #e8f5e8; padding: 1.5rem; border-radius: 15px; 
                        border-left: 5px solid #4CAF50; margin-bottom: 1rem;">
                <h6 style="margin: 0 0 1rem 0; color: #2E7D32; font-weight: 600;">
                    🛍️ 购物行为分析
                </h6>
                <div style="color: #333; font-size: 0.9rem;">
                    <p style="margin: 0.3rem 0;"><strong>总订单：</strong>{shopping_behavior.get('total_orders', 0)} 笔</p>
                    <p style="margin: 0.3rem 0;"><strong>消费总额：</strong>¥{shopping_behavior.get('total_amount', 0):.1f}</p>
                    <p style="margin: 0.3rem 0;"><strong>客单价：</strong>¥{shopping_behavior.get('average_order_value', 0):.1f}</p>
                    <p style="margin: 0.3rem 0;"><strong>消费模式：</strong>{shopping_behavior.get('behavior_pattern', '理性消费型')}</p>
                    <p style="margin: 0.3rem 0;"><strong>购物频率：</strong>{shopping_behavior.get('shopping_frequency', '中频')}</p>
                </div>
            </div>
            """, unsafe_allow_html=True)
        
        with col2:
            growth_journey = report.get('growth_journey', {})
            st.markdown(f"""
            <div style="background: #fff3cd; padding: 1.5rem; border-radius: 15px; 
                        border-left: 5px solid #FFC107; margin-bottom: 1rem;">
                <h6 style="margin: 0 0 1rem 0; color: #856404; font-weight: 600;">
                    📈 成长轨迹分析
                </h6>
                <div style="color: #333; font-size: 0.9rem;">
                    <p style="margin: 0.3rem 0;"><strong>账户天数：</strong>{growth_journey.get('account_age_days', 0)} 天</p>
                    <p style="margin: 0.3rem 0;"><strong>成长阶段：</strong>{growth_journey.get('growth_stage', '探索期')}</p>
                    <p style="margin: 0.3rem 0;"><strong>会员等级：</strong>{growth_journey.get('membership_level', '普通会员')}</p>
                    <p style="margin: 0.3rem 0;"><strong>积分余额：</strong>{growth_journey.get('points_balance', 0)} 分</p>
                    <p style="margin: 0.3rem 0;"><strong>订单总数：</strong>{growth_journey.get('total_orders', 0)} 笔</p>
                </div>
            </div>
            """, unsafe_allow_html=True)
        
        with col3:
            insights = report.get('insights', [])
            st.markdown("""
            <div style="background: #e7f3ff; padding: 1.5rem; border-radius: 15px; 
                        border-left: 5px solid #2196F3; margin-bottom: 1rem;">
                <h6 style="margin: 0 0 1rem 0; color: #1565C0; font-weight: 600;">
                    💡 AI 个性化洞察
                </h6>
            """, unsafe_allow_html=True)
            
            if insights:
                for insight in insights[:4]:  # 显示前4条洞察
                    st.markdown(f"""
                    <div style="background: rgba(33, 150, 243, 0.1); padding: 0.8rem; 
                               margin: 0.5rem 0; border-radius: 8px; color: #333;">
                        <small>💡 {insight}</small>
                    </div>
                    """, unsafe_allow_html=True)
            else:
                st.markdown("""
                <p style="color: #666; font-size: 0.9rem; margin: 0;">
                    暂无个性化洞察建议
                </p>
                """, unsafe_allow_html=True)
            
            st.markdown("</div>", unsafe_allow_html=True)
        
        # 喜好分析
        favorite_categories = shopping_behavior.get('favorite_categories', [])
        if favorite_categories:
            st.markdown("""
            <div style="background: #f3e5f5; padding: 1.5rem; border-radius: 15px; 
                        border-left: 5px solid #9C27B0; margin-bottom: 1rem;">
                <h6 style="margin: 0 0 1rem 0; color: #7B1FA2; font-weight: 600;">
                    ❤️ 购物偏好分析
                </h6>
            """, unsafe_allow_html=True)
            
            # 显示偏好类别
            categories_text = " | ".join(favorite_categories[:5])
            st.markdown(f"""
            <div style="display: flex; flex-wrap: wrap; gap: 0.5rem;">
                <span style="color: #333; font-size: 0.9rem;"><strong>偏好类别：</strong></span>
                <span style="color: #7B1FA2; font-weight: 500;">{categories_text}</span>
            </div>
            """, unsafe_allow_html=True)
            
            st.markdown("</div>", unsafe_allow_html=True)
        
        st.markdown("</div>", unsafe_allow_html=True)
    
    # 左右布局
    col_left, col_right = st.columns([3, 2])
    
    with col_left:
        # 最近购买历史
        st.markdown("""
        <div style="background: white; padding: 1.5rem; border-radius: 15px; 
                    box-shadow: 0 4px 16px rgba(0,0,0,0.08); margin-bottom: 1.5rem; border: 1px solid #f0f0f0;">
            <h4 style="margin: 0 0 1rem 0; color: #333; font-weight: 600;">
                <span style="color: #e3000b;">📦</span> 最近购买
            </h4>
        """, unsafe_allow_html=True)
        
        recent_purchases = get_user_purchase_history(username)
        if recent_purchases:
            for i, item in enumerate(recent_purchases[:5]):  # 显示最近5个
                st.markdown(f"""
                <div style="display: flex; justify-content: space-between; align-items: center; 
                           padding: 0.8rem; margin: 0.5rem 0; background: #f8f9fa; border-radius: 10px; 
                           border-left: 3px solid #e3000b;">
                    <div>
                        <h6 style="margin: 0; font-size: 0.9rem; color: #333;">
                            {item.get('name', '未知商品')}
                        </h6>
                        <p style="margin: 0.2rem 0; font-size: 0.8rem; color: #666;">
                            {item.get('category', '未知类别')} | {item.get('merchant', '未知商家')}
                        </p>
                    </div>
                    <div style="text-align: right;">
                        <span class="price-badge" style="font-size: 0.8rem;">¥{item.get('price', 0)}</span>
                    </div>
                </div>
                """, unsafe_allow_html=True)
            
            if len(recent_purchases) > 5:
                st.markdown(f"""
                <div style="text-align: center; margin-top: 1rem;">
                    <small style="color: #666;">还有 {len(recent_purchases) - 5} 件商品...</small>
                </div>
                """, unsafe_allow_html=True)
        else:
            st.markdown("""
            <div style="text-align: center; padding: 2rem; color: #666;">
                <div style="font-size: 3rem; margin-bottom: 1rem;">📭</div>
                <p style="margin: 0; font-size: 0.9rem;">暂无购买记录</p>
                <p style="margin: 0.3rem 0 0 0; font-size: 0.8rem;">快去购买您喜欢的商品吧！</p>
            </div>
            """, unsafe_allow_html=True)
        
        st.markdown("</div>", unsafe_allow_html=True)
    
    with col_right:
        # 每日签到区域（如果积分系统可用）
        if POINTS_SYSTEM_AVAILABLE:
            st.markdown("""
            <div style="background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%); 
                        padding: 1.5rem; border-radius: 15px; margin-bottom: 1.5rem; 
                        box-shadow: 0 4px 16px rgba(255, 193, 7, 0.3); color: white;">
                <h5 style="margin: 0 0 1rem 0; font-weight: 600;">📅 每日签到</h5>
            """, unsafe_allow_html=True)
            
            if st.button("🎯 立即签到领积分", use_container_width=True, key="daily_checkin"):
                login_result = daily_login(user_email)
                if login_result["success"]:
                    st.success(login_result["message"])
                    st.balloons()
                    time.sleep(1)
                    st.rerun()
                else:
                    st.info(login_result["message"])
            
            st.markdown("</div>", unsafe_allow_html=True)
        
        # 积分动态（如果积分系统可用）
        if POINTS_SYSTEM_AVAILABLE:
            st.markdown("""
            <div style="background: white; padding: 1.5rem; border-radius: 15px; 
                        box-shadow: 0 4px 16px rgba(0,0,0,0.08); margin-bottom: 1.5rem; border: 1px solid #f0f0f0;">
                <h5 style="margin: 0 0 1rem 0; color: #333; font-weight: 600;">
                    <span style="color: #ffc107;">�</span> 积分动态
                </h5>
            """, unsafe_allow_html=True)
            
            # 可兑换奖励
            available_rewards = get_available_rewards()
            current_points = get_user_points(user_email)
            affordable_rewards = [r for r in available_rewards if r["points_required"] <= current_points]
            
            if affordable_rewards:
                st.markdown("<h6 style='margin: 0 0 0.5rem 0; color: #333;'>🏆 可兑换奖励</h6>", unsafe_allow_html=True)
                for reward in affordable_rewards[:3]:
                    st.markdown(f"""
                    <div style="padding: 0.5rem; margin: 0.3rem 0; background: #e8f5e8; 
                               border-radius: 8px; border-left: 3px solid #28a745;">
                        <small style="color: #333;">🎁 {reward['name']} ({reward['points_required']} 积分)</small>
                    </div>
                    """, unsafe_allow_html=True)
            
            # 最近积分记录
            points_history = get_user_points_history(user_email)
            if points_history:
                st.markdown("<h6 style='margin: 1rem 0 0.5rem 0; color: #333;'>📈 最近记录</h6>", unsafe_allow_html=True)
                recent_points = points_history[-3:]
                recent_points.reverse()
                
                for record in recent_points:
                    points = record.get("points", 0)
                    reason = record.get("reason", "未知")
                    if points > 0:
                        st.markdown(f"""
                        <div style="padding: 0.3rem 0.5rem; margin: 0.2rem 0; background: #e8f5e8; 
                                   border-radius: 5px; font-size: 0.8rem;">
                            <span style="color: #28a745;">✅ {reason} (+{points})</span>
                        </div>
                        """, unsafe_allow_html=True)
                    else:
                        st.markdown(f"""
                        <div style="padding: 0.3rem 0.5rem; margin: 0.2rem 0; background: #f8d7da; 
                                   border-radius: 5px; font-size: 0.8rem;">
                            <span style="color: #dc3545;">❌ {reason} ({points})</span>
                        </div>
                        """, unsafe_allow_html=True)
            
            st.markdown("</div>", unsafe_allow_html=True)
        
        # 购物车快捷入口
        cart_items = get_cart_items(user_email)
        cart_count = sum(item['quantity'] for item in cart_items)
        
        if cart_count > 0:
            cart_total = sum(item['price'] * item['quantity'] for item in cart_items)
            st.markdown(f"""
            <div style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%); 
                        padding: 1.5rem; border-radius: 15px; color: white; text-align: center;
                        box-shadow: 0 4px 16px rgba(40, 167, 69, 0.3);">
                <h5 style="margin: 0 0 0.5rem 0; font-weight: 600;">🛒 您的购物车</h5>
                <p style="margin: 0; font-size: 1.1rem; font-weight: 700;">{cart_count} 件商品</p>
                <p style="margin: 0.3rem 0 0 0; font-size: 0.9rem; opacity: 0.9;">总计: ¥{cart_total:.2f}</p>
            </div>
            """, unsafe_allow_html=True)
        else:
            st.markdown("""
            <div style="background: #6c757d; padding: 1.5rem; border-radius: 15px; 
                        color: white; text-align: center;">
                <h5 style="margin: 0 0 0.5rem 0; font-weight: 600;">🛒 购物车</h5>
                <p style="margin: 0; font-size: 0.9rem; opacity: 0.9;">暂无商品</p>
            </div>
            """, unsafe_allow_html=True)

def show_recommendation_page():
    """显示商品推荐页面"""
    st.markdown("### 🛍️ 智能商品推荐系统")
    
    username = st.session_state.user.get("username", "")
    
    # 推荐设置
    st.markdown("#### 🎯 推荐设置")
    top_k = st.slider("推荐商品数量", 1, 10, 5)
    
    # 初始化推荐商品状态
    if 'current_recommendations' not in st.session_state:
        st.session_state.current_recommendations = []
    
    # 获取推荐商品
    if st.button("🔄 获取个性化推荐", use_container_width=True):
        with st.spinner("🤖 智能推荐系统正在分析您的偏好..."):
            try:
                recommendations = get_recommendation_from_api(username)
                
                if recommendations:
                    st.session_state.current_recommendations = recommendations[:top_k]
                    st.success(f"🎉 为您推荐了 {len(st.session_state.current_recommendations)} 件商品")
                else:
                    st.info("💡 暂时无法获取推荐商品，请稍后再试")
            except Exception as e:
                st.error(f"❌ 获取推荐失败：{str(e)}")
    
    # 显示推荐商品
    if st.session_state.current_recommendations:
        st.markdown("#### 🛍️ 推荐商品")
        
        # 显示推荐商品 - 使用网格布局
        cols = st.columns(3)
        for i, product in enumerate(st.session_state.current_recommendations):
            with cols[i % 3]:
                st.markdown(f"""
                <div class="product-card">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
                        <h5 style="margin: 0; font-size: 0.9rem;">🛍️ {product.get('name', '未知商品')}</h5>
                        <span style="background: #007bff; color: white; padding: 0.1rem 0.3rem; border-radius: 10px; font-size: 0.7rem;">
                            #{i+1}
                        </span>
                    </div>
                    <p style="margin: 0.2rem 0; font-size: 0.8rem;"><strong>💰 ¥{product.get('price', 0)}</strong></p>
                    <p style="margin: 0.2rem 0; font-size: 0.75rem; color: #666;">🏷️ {product.get('category', '未知')}</p>
                    <p style="margin: 0.2rem 0; font-size: 0.75rem; color: #666;">🏪 {product.get('merchant', '未知')}</p>
                </div>
                """, unsafe_allow_html=True)
                
                # 购买按钮 - 使用唯一的key
                col_cart, col_buy = st.columns(2)
                with col_cart:
                    cart_key = f"rec_cart_{product['id']}_{i}"
                    if st.button("🛒 加入购物车", key=cart_key, use_container_width=True):
                        if add_to_cart(product['id'], 1):
                            st.success("✅ 已添加到购物车")
                            time.sleep(1)
                            st.rerun()
                        else:
                            st.error("❌ 添加失败")
                
                with col_buy:
                    buy_key = f"rec_buy_{product['id']}_{i}"
                    if st.button("💳 立即购买", key=buy_key, use_container_width=True):
                        result = process_purchase(username, product['id'], 1, st.session_state.user.get('email'))
                        if result["success"]:
                            st.success("✅ 购买成功")
                            st.info(f"订单号: {result['order_id']}")
                            st.balloons()
                            time.sleep(1)
                            st.rerun()
                        else:
                            st.error(f"❌ 购买失败: {result['message']}")
    
    # 用户偏好分析
    st.markdown("### � 用户偏好分析")
    
    col1, col2 = st.columns(2)
    
    with col1:
        st.markdown("#### �🛍️ 购买历史")
        history = get_user_purchase_history(username)
        if history:
            for item in history:
                with st.expander(f"📦 {item.get('name', '未知商品')} - ¥{item.get('price', 0)}"):
                    st.write(f"**🏷️ 分类：** {item.get('category', '未知')}")
                    st.write(f"**🏪 商家：** {item.get('merchant', '未知')}")
                    st.write(f"**🏷️ 标签：** {', '.join(item.get('tags', []))}")
        else:
            st.info("📭 您好！您还没有购买记录，快去选购一些商品吧！")
    
    with col2:
        st.markdown("#### 🎯 用户画像")
        try:
            recommendation_service = get_recommendation_service()
            user_profile = recommendation_service.describe_user(username)
            st.markdown(f"""
            <div style="background: #e3f2fd; padding: 1rem; border-radius: 8px; border-left: 4px solid #2196f3;">
                <h5>👤 个人画像</h5>
                <p>{user_profile}</p>
            </div>
            """, unsafe_allow_html=True)
        except Exception as e:
            st.info("📊 正在分析用户偏好...")

def show_chat_page():
    """显示客服聊天页面"""
    st.markdown("### 💬 智能客服助手")
    
    # 显示AI助手状态
    col1, col2 = st.columns([3, 1])
    
    with col1:
        if AI_ASSISTANT_AVAILABLE and st.session_state.ai_assistant is not None:
            # 检查使用的是哪种AI助手
            if isinstance(st.session_state.ai_assistant, LocalOllamaAssistant):
                st.info("🤖 本地Ollama AI客服已启用（备用） - 为您提供智能服务")
            else:
                st.success("🤖 硅基流动AI智能客服已启用 - 为您提供更智能的服务")
        elif AI_ASSISTANT_AVAILABLE:
            st.warning("⚠️ AI助手正在初始化中...")
            if st.button("🔄 重新初始化AI助手"):
                init_ai_assistant()
                st.rerun()
        else:
            st.info("📝 使用基础客服服务（可能需要安装依赖包）")
    
    with col2:
        if st.button("🗑️ 清空对话", help="清空当前聊天记录"):
            st.session_state.chat_history = []
            st.session_state.customer_service_session = None
            st.rerun()
    
    # 聊天历史
    chat_container = st.container()
    
    with chat_container:
        if st.session_state.chat_history:
            for i, message in enumerate(st.session_state.chat_history):
                if message["role"] == "user":
                    st.markdown(f"""
                    <div style="text-align: right; margin: 0.5rem 0;">
                        <div style="background: #007bff; color: white; padding: 0.5rem 1rem; 
                                   border-radius: 15px; display: inline-block; max-width: 70%;">
                            {message["content"]}
                        </div>
                    </div>
                    """, unsafe_allow_html=True)
                else:
                    st.markdown(f"""
                    <div style="text-align: left; margin: 0.5rem 0;">
                        <div style="background: #f8f9fa; color: #333; padding: 0.5rem 1rem; 
                                   border-radius: 15px; display: inline-block; max-width: 70%;">
                            🤖 {message["content"]}
                        </div>
                    </div>
                    """, unsafe_allow_html=True)
        else:
            st.info("👋 您好！我是智能客服助手，有什么可以帮助您的吗？")
    
    # 输入框
    with st.form(key="chat_form", clear_on_submit=True):
        col1, col2 = st.columns([4, 1])
        
        with col1:
            user_input = st.text_input("输入您的问题...", key="chat_input", placeholder="例如：我想查询订单状态")
        
        with col2:
            send_button = st.form_submit_button("发送", use_container_width=True)
        
        # 处理发送消息
        if send_button and user_input.strip():
            # 添加用户消息
            st.session_state.chat_history.append({"role": "user", "content": user_input.strip()})
            
            # 生成AI回复
            with st.spinner("正在生成回复..."):
                response = generate_chat_response(user_input.strip())
                st.session_state.chat_history.append({"role": "assistant", "content": response})
            
            st.rerun()
    
    # 快捷问题
    st.markdown("### 🔍 常见问题")
    quick_questions = [
        "如何退货？",
        "积分规则是什么？", 
        "支付方式有哪些？",
        "配送时间是多久？",
        "积分如何兑换？",
        "会员有什么权益？",
        "购物车怎么管理？",
        "AI助手有什么功能？"
    ]
    
    cols = st.columns(2)
    for i, question in enumerate(quick_questions):
        with cols[i % 2]:
            # 使用唯一的按钮key，避免重复
            if st.button(question, key=f"quick_question_{i}"):
                # 添加用户消息
                st.session_state.chat_history.append({"role": "user", "content": question})
                
                # 生成AI回复
                with st.spinner("正在生成回复..."):
                    response = generate_chat_response(question)
                    st.session_state.chat_history.append({"role": "assistant", "content": response})
                
                st.rerun()

def generate_chat_response(question: str) -> str:
    """生成聊天回复"""
    # 首先尝试从知识库搜索答案
    try:
        # 导入知识库搜索函数
        from smart_assistant.assistant.tools import search_knowledge_base
        
        # 搜索知识库
        knowledge_answer = search_knowledge_base(question)
        
        if knowledge_answer:
            # 如果找到知识库答案，优先使用
            return f"根据我们的知识库，{knowledge_answer}"
    except Exception as e:
        print(f"知识库搜索失败: {e}")
    
    # 如果AI助手可用，使用智能回复
    if st.session_state.ai_assistant is not None:
        try:
            # 创建客服会话（如果还没有）
            if st.session_state.customer_service_session is None:
                try:
                    session_id = f"CS_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
                    st.session_state.customer_service_session = CustomerServiceSession(session_id)
                except Exception as e:
                    print(f"创建客服会话失败: {e}")
                    st.session_state.customer_service_session = None
            
            # 检查是否是本地Ollama助手
            if isinstance(st.session_state.ai_assistant, LocalOllamaAssistant):
                # 使用本地Ollama助手
                response = st.session_state.ai_assistant.chat(
                    user_input=question,
                    use_tools=False,
                    show_thinking=False
                )
            else:
                # 使用硅基流动助手（SmartAssistant）
                user_info = st.session_state.user
                context = f"""
作为电商平台客服助手，请简洁专业地回答用户问题。

用户：{user_info.get('username', '未知')}
问题：{question}

请保持回复简洁明了，直接回答问题，不要显示思考过程。
"""
                response = st.session_state.ai_assistant.chat(
                    user_input=context,
                    use_tools=False,
                    show_thinking=False
                )
            
            # 添加消息到客服会话（如果会话存在）
            if st.session_state.customer_service_session is not None:
                try:
                    st.session_state.customer_service_session.add_message(question, "customer")
                    st.session_state.customer_service_session.add_message(response, "assistant")
                except Exception as e:
                    print(f"添加消息到会话失败: {e}")
            
            # 清理回复格式（主要针对硅基流动的回复）
            if "💬 **回复**：" in response:
                response = response.split("💬 **回复**：")[1].strip()
            elif "回复：" in response:
                response = response.split("回复：")[1].strip()
            
            # 删除可能的思考部分（针对deepseek-r1模型）
            if "<think>" in response and "</think>" in response:
                response = response.split("</think>")[-1].strip()
            
            return response
            
        except Exception as e:
            print(f"AI助手回复失败: {e}")
            # 显示错误但不阻止使用
            return f"AI助手暂时遇到问题，为您提供基础服务：\n\n{generate_fallback_response(question)}"
    else:
        # 如果AI助手不可用，使用备用回复
        return generate_fallback_response(question)

def generate_fallback_response(question: str) -> str:
    """生成备用回复（规则匹配）"""
    # 首先尝试从知识库搜索答案
    try:
        # 导入知识库搜索函数
        from smart_assistant.assistant.tools import search_knowledge_base
        
        # 搜索知识库
        knowledge_answer = search_knowledge_base(question)
        
        if knowledge_answer:
            # 如果找到知识库答案，直接返回
            return knowledge_answer
    except Exception as e:
        print(f"知识库搜索失败: {e}")
    
    # 如果知识库搜索失败，使用原有的规则匹配
    question_lower = question.lower()
    
    if "订单" in question_lower:
        return "您好！关于订单问题，请您前往【订单管理】页面查看详细信息。如有其他问题，我随时为您服务。"
    elif "退款" in question_lower or "退货" in question_lower:
        return "关于退款事宜，您可以在订单详情页面提交退款申请，一般3-5个工作日内处理完成。"
    elif "换货" in question_lower:
        return "商品如有质量问题或规格不符，支持7天内免费换货。换货需保持商品完整包装，配件齐全。人为损坏不支持换货。"
    elif "推荐" in question_lower or "商品" in question_lower:
        return "我为您推荐了一些商品！您可以在【商品推荐】页面查看个性化推荐。"
    elif "信息" in question_lower or "修改" in question_lower:
        return "您可以在【个人中心】页面修改个人信息，包括昵称、地址等。"
    elif "配送" in question_lower or "物流" in question_lower or "发货" in question_lower:
        return "一般情况下，订单会在24小时内发货，3-5个工作日内送达。偏远地区可能需要额外1-2天。急需的话可以选择次日达服务（需额外付费）。"
    elif "支付" in question_lower or "付款" in question_lower:
        return "我们支持微信支付、支付宝、银行卡、信用卡等多种支付方式。所有支付都采用SSL加密，确保您的资金安全。"
    elif "客服" in question_lower or "联系" in question_lower:
        return "我们的客服工作时间是周一至周日 9:00-18:00。客服热线：400-123-4567。也可以通过在线客服或邮箱service@example.com联系我们。"
    elif "会员" in question_lower:
        return "会员享有专属折扣、优先客服、生日礼品、积分翻倍、免费配送等多项权益。升级VIP会员还可享受更多特权。"
    elif "积分" in question_lower:
        return "消费1元获得1积分，积分可用于兑换优惠券和礼品。积分有效期2年，VIP会员积分永久有效。签到、评价等行为也可获得积分奖励。"
    elif "发票" in question_lower:
        return "我们支持开具电子发票和纸质发票。电子发票下单后立即发送至邮箱，纸质发票需要额外1-2个工作日。可开具个人或企业发票。"
    elif "售后" in question_lower or "保修" in question_lower:
        return "产品出现质量问题，我们提供免费维修或更换服务。保修期内免费，保修期外提供有偿维修。支持全国联保。"
    elif "价格" in question_lower or "降价" in question_lower:
        return "购买后7天内如商品降价，可申请价保退差价。参与活动商品除外。VIP会员享受30天价保服务。"
    else:
        return "感谢您的咨询！如果您有其他问题，请随时联系我们的客服团队。"

def save_user_data(users_data):
    """保存用户数据到文件"""
    try:
        with open(PROJECT_ROOT / "data" / "users.json", 'w', encoding='utf-8') as f:
            json.dump(users_data, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        st.error(f"保存用户数据失败：{e}")
        return False

# 导入积分系统
try:
    from utils.points_system import (
        get_user_points,
        get_user_points_history,
        add_points,
        claim_reward,
        get_user_rewards,
        daily_login,
        add_purchase_points,
        get_available_rewards,
        POINTS_RULES
    )
    POINTS_SYSTEM_AVAILABLE = True
    print("✅ 积分系统模块加载成功")
except ImportError as e:
    print(f"⚠️ 无法导入积分系统: {e}")
    POINTS_SYSTEM_AVAILABLE = False
    
    # 创建备用的积分系统函数
    def get_user_points(user_id: str) -> int:
        return 0
    
    def get_user_points_history(user_id: str) -> list:
        return []
    
    def add_points(user_id: str, points: int, reason: str, **kwargs) -> bool:
        return False
    
    def claim_reward(user_id: str, reward_id: str) -> dict:
        return {"success": False, "message": "积分系统不可用"}
    
    def get_user_rewards(user_id: str) -> list:
        return []
    
    def daily_login(user_id: str) -> dict:
        return {"success": False, "message": "积分系统不可用", "points": 0}
    
    def add_purchase_points(user_id: str, order_id: str, amount: float) -> dict:
        return {"success": False, "message": "积分系统不可用", "points": 0}
    
    def get_available_rewards() -> list:
        return []
    
    POINTS_RULES = {}

# 导入生涯分析系统
try:
    # 生涯分析代理类
    class CareerOverviewAgent:
        """生涯概览分析代理 - 基于用户购物行为的个性化分析"""
        
        def __init__(self):
            self.project_root = Path(__file__).parent
            self.data_dir = self.project_root / "data"
            
        def load_user_data(self, user_id: str) -> Dict[str, Any]:
            """加载用户基础数据"""
            try:
                users_file = self.data_dir / "users.json"
                if users_file.exists():
                    with open(users_file, 'r', encoding='utf-8') as f:
                        users_data = json.load(f)
                        return users_data.get("users", {}).get(user_id, {})
                return {}
            except Exception as e:
                print(f"加载用户数据失败: {e}")
                return {}
        
        def load_orders_data(self, user_id: str) -> List[Dict]:
            """加载用户订单数据"""
            try:
                orders_file = self.data_dir / "orders.json"
                if orders_file.exists():
                    with open(orders_file, 'r', encoding='utf-8') as f:
                        orders_data = json.load(f)
                        # 订单数据结构: {"orders": {"email": [orders_list]}}
                        orders_dict = orders_data.get("orders", {})
                        
                        # 首先尝试直接通过 user_id (email) 获取订单
                        user_orders = orders_dict.get(user_id, [])
                        
                        # 如果没有找到，遍历所有订单查找匹配的
                        if not user_orders:
                            for email, orders_list in orders_dict.items():
                                for order in orders_list:
                                    if (order.get("user_email") == user_id or 
                                        order.get("username") == user_id or
                                        email == user_id):
                                        user_orders.append(order)
                        
                        return user_orders
                return []
            except Exception as e:
                print(f"加载订单数据失败: {e}")
                return []
        
        def load_points_data(self, user_id: str) -> Dict[str, Any]:
            """加载用户积分数据"""
            try:
                points_file = self.data_dir / "user_points.json"
                if points_file.exists():
                    with open(points_file, 'r', encoding='utf-8') as f:
                        points_data = json.load(f)
                        # 积分数据结构: {"points": {"user_id": balance}, "transactions": [...]}
                        balance = points_data.get("points", {}).get(user_id, 0)
                        
                        # 获取用户的积分历史记录
                        transactions = points_data.get("transactions", [])
                        user_history = [tx for tx in transactions if tx.get("user_id") == user_id]
                        
                        return {
                            "balance": balance,
                            "history": user_history
                        }
                return {"balance": 0, "history": []}
            except Exception as e:
                print(f"加载积分数据失败: {e}")
                return {"balance": 0, "history": []}
        
        def load_membership_data(self, user_id: str) -> Dict[str, Any]:
            """加载用户会员数据"""
            try:
                membership_file = self.data_dir / "membership.json"
                if membership_file.exists():
                    with open(membership_file, 'r', encoding='utf-8') as f:
                        membership_data = json.load(f)
                        # 会员数据结构: {"memberships": {"username": {...}}}
                        memberships = membership_data.get("memberships", {})
                        
                        # 首先尝试直接通过 user_id 获取
                        member_data = memberships.get(user_id)
                        if member_data:
                            return member_data
                        
                        # 如果没找到，需要通过邮箱获取用户名，然后查找会员数据
                        # 先获取用户数据来获取用户名
                        user_data = self.load_user_data(user_id)
                        username = user_data.get("username", "")
                        if username and username in memberships:
                            return memberships[username]
                        
                        # 如果都没找到，返回默认值
                        return {"level": "普通会员", "expires": None}
                return {"level": "普通会员", "expires": None}
            except Exception as e:
                print(f"加载会员数据失败: {e}")
                return {"level": "普通会员", "expires": None}
        
        def analyze_shopping_behavior(self, orders: List[Dict]) -> Dict[str, Any]:
            """分析购物行为"""
            if not orders:
                return {
                    "total_orders": 0,
                    "total_amount": 0.0,
                    "average_order_value": 0.0,
                    "behavior_pattern": "新用户",
                    "favorite_categories": [],
                    "shopping_frequency": "无"
                }
            
            total_orders = len(orders)
            total_amount = sum(float(order.get("total_amount", 0)) for order in orders)
            average_order_value = total_amount / total_orders if total_orders > 0 else 0
            
            # 分析购物行为模式
            if average_order_value > 500:
                behavior_pattern = "高端消费型"
            elif average_order_value > 200:
                behavior_pattern = "理性消费型"
            elif total_orders > 10:
                behavior_pattern = "频繁购买型"
            else:
                behavior_pattern = "偶尔购买型"
            
            # 分析商品类别偏好
            category_count = {}
            for order in orders:
                items = order.get("items", [])
                # 处理不同的items格式
                if isinstance(items, list):
                    for item in items:
                        if isinstance(item, dict):
                            # 如果item是字典对象
                            category = item.get("category", "其他")
                        elif isinstance(item, str):
                            # 如果item是字符串，尝试从商品名称推断类别
                            if "手机" in item or "phone" in item.lower():
                                category = "数码电子"
                            elif "耳机" in item or "headphone" in item.lower():
                                category = "数码配件"
                            elif "充电" in item or "power" in item.lower():
                                category = "数码配件"
                            elif "服装" in item or "衣服" in item:
                                category = "服装"
                            elif "食品" in item or "零食" in item:
                                category = "食品"
                            else:
                                category = "其他"
                        else:
                            category = "其他"
                        category_count[category] = category_count.get(category, 0) + 1
            
            favorite_categories = sorted(category_count.items(), key=lambda x: x[1], reverse=True)[:3]
            
            # 购物频率分析
            if total_orders > 20:
                shopping_frequency = "高频"
            elif total_orders > 10:
                shopping_frequency = "中频"
            elif total_orders > 5:
                shopping_frequency = "低频"
            else:
                shopping_frequency = "偶尔"
            
            return {
                "total_orders": total_orders,
                "total_amount": total_amount,
                "average_order_value": average_order_value,
                "behavior_pattern": behavior_pattern,
                "favorite_categories": [cat[0] for cat in favorite_categories],
                "shopping_frequency": shopping_frequency
            }
        
        def analyze_growth_journey(self, user_data: Dict, orders: List[Dict], 
                                  points_data: Dict, membership_data: Dict) -> Dict[str, Any]:
            """分析成长轨迹"""
            # 计算账户年龄
            created_at = user_data.get("created_at")
            if created_at:
                try:
                    if isinstance(created_at, str):
                        created_date = datetime.fromisoformat(created_at.replace("Z", "+00:00"))
                    else:
                        created_date = datetime.fromtimestamp(created_at)
                    account_age_days = (datetime.now() - created_date.replace(tzinfo=None)).days
                except:
                    account_age_days = 0
            else:
                account_age_days = 0
            
            # 成长阶段判断
            if account_age_days < 30:
                growth_stage = "新手探索期"
            elif account_age_days < 90:
                growth_stage = "快速适应期"
            elif account_age_days < 365:
                growth_stage = "稳定发展期"
            else:
                growth_stage = "成熟用户期"
            
            return {
                "account_age_days": account_age_days,
                "membership_level": membership_data.get("level", "普通会员"),
                "points_balance": points_data.get("balance", 0),
                "growth_stage": growth_stage,
                "total_orders": len(orders),
                "registration_date": created_at
            }
        
        def generate_insights(self, shopping_behavior: Dict, growth_journey: Dict) -> List[str]:
            """生成个性化洞察"""
            insights = []
            
            # 获取关键数据
            behavior_pattern = shopping_behavior.get("behavior_pattern", "")
            growth_stage = growth_journey.get("growth_stage", "")
            total_orders = shopping_behavior.get("total_orders", 0)
            total_amount = shopping_behavior.get("total_amount", 0)
            points_balance = growth_journey.get("points_balance", 0)
            account_age_days = growth_journey.get("account_age_days", 0)
            shopping_frequency = shopping_behavior.get("shopping_frequency", "")
            favorite_categories = shopping_behavior.get("favorite_categories", [])
            
            print(f"🔍 洞察生成调试 - 行为模式: {behavior_pattern}, 成长阶段: {growth_stage}, 订单数: {total_orders}, 消费额: {total_amount}")
            
            # 基于购物行为的洞察
            if behavior_pattern == "高端消费型":
                insights.append("您展现出优秀的消费品味，偏好高品质商品")
                insights.append("建议关注我们的尊享会员服务，享受更多专属权益")
            elif behavior_pattern == "理性消费型":
                insights.append("您展现出优秀的理财规划能力，消费理性且有度")
                insights.append("建议继续保持理性消费习惯，可关注我们的优惠活动")
            elif behavior_pattern == "频繁购买型":
                insights.append("您是我们的活跃用户，购买频率很高")
                insights.append("建议升级会员等级，享受更多购物优惠")
            elif behavior_pattern == "偶尔购买型":
                insights.append("您的购物习惯相对谨慎，这体现了良好的消费理念")
                insights.append("我们会为您推荐性价比高的优质商品")
            elif behavior_pattern == "新用户":
                insights.append("欢迎您加入我们的购物平台")
                insights.append("建议先浏览热门商品，了解平台特色")
            
            # 基于成长轨迹的洞察
            if growth_stage == "新手探索期":
                insights.append("您正处于平台探索阶段，建议多尝试不同类别的商品")
                insights.append("新用户专享优惠活动正在进行，不要错过")
            elif growth_stage == "快速适应期":
                insights.append("您已经熟悉了平台操作，购物体验在快速提升")
                insights.append("可以关注我们的会员升级优惠，享受更多权益")
            elif growth_stage == "稳定发展期":
                insights.append("您已成为我们的稳定用户，购物体验日趋成熟")
                insights.append("建议关注积分兑换活动，充分利用您的消费积累")
            elif growth_stage == "成熟用户期":
                insights.append("感谢您长期以来的信任和支持")
                insights.append("您的购物经验丰富，可以考虑成为我们的品牌推荐官")
            
            # 基于订单数量的洞察
            if total_orders >= 10:
                insights.append(f"您已完成 {total_orders} 笔订单，是我们的忠实用户")
            elif total_orders >= 5:
                insights.append(f"您已有 {total_orders} 次购物经历，对平台信任度很高")
            elif total_orders >= 1:
                insights.append(f"感谢您的 {total_orders} 次购买，期待为您提供更好的服务")
            
            # 基于消费金额的洞察
            if total_amount >= 2000:
                insights.append(f"您的累计消费达到 ¥{total_amount:.0f}，体现了对品质的追求")
            elif total_amount >= 500:
                insights.append(f"您的消费金额为 ¥{total_amount:.0f}，消费习惯良好")
            elif total_amount > 0:
                insights.append(f"感谢您 ¥{total_amount:.0f} 的消费支持")
            
            # 基于积分余额的洞察
            if points_balance > 1000:
                insights.append("您的积分余额充足，可以兑换心仪的奖品")
            elif points_balance > 500:
                insights.append("您的积分即将达到兑换门槛，继续购物可获得更多积分")
            elif points_balance > 0:
                insights.append(f"您当前有 {points_balance} 积分，可用于购物抵扣")
            
            # 基于账户年龄的洞察
            if account_age_days >= 365:
                insights.append(f"您已陪伴我们 {account_age_days} 天，是我们的老朋友了")
            elif account_age_days >= 90:
                insights.append(f"注册 {account_age_days} 天来，您对平台的支持让我们倍感温暖")
            elif account_age_days > 0:
                insights.append(f"加入我们 {account_age_days} 天，期待与您建立长期的购物关系")
            
            # 基于购物频率的洞察
            if shopping_frequency == "高频":
                insights.append("您的购物频率很高，是我们最活跃的用户之一")
            elif shopping_frequency == "中频":
                insights.append("您保持着适中的购物频率，消费习惯很健康")
            elif shopping_frequency == "低频":
                insights.append("您的购物相对谨慎，每次购买都经过深思熟虑")
            
            # 基于商品偏好的洞察
            if favorite_categories:
                top_category = favorite_categories[0]
                insights.append(f"您特别偏爱{top_category}类商品，我们会为您推荐更多相关优质产品")
            
            # 确保至少有一些基础洞察
            if not insights:
                insights.extend([
                    "感谢您选择我们的平台，我们致力于为您提供优质的购物体验",
                    "建议您多关注我们的促销活动，享受更多购物优惠",
                    "您的每一次购买都是对我们的信任，我们将继续努力提升服务质量"
                ])
            
            print(f"💡 生成了 {len(insights)} 条洞察")
            return insights
        
        def _calculate_career_score(self, shopping_behavior: Dict, growth_journey: Dict) -> int:
            """计算生涯评分（0-100）"""
            score = 0
            
            # 订单数量评分 (30分)
            total_orders = shopping_behavior.get("total_orders", 0)
            if total_orders >= 20:
                score += 30
            elif total_orders >= 10:
                score += 20
            elif total_orders >= 5:
                score += 10
            
            # 消费金额评分 (25分)
            total_amount = shopping_behavior.get("total_amount", 0)
            if total_amount >= 5000:
                score += 25
            elif total_amount >= 2000:
                score += 20
            elif total_amount >= 1000:
                score += 15
            elif total_amount >= 500:
                score += 10
            
            # 账户年龄评分 (20分)
            account_age = growth_journey.get("account_age_days", 0)
            if account_age >= 365:
                score += 20
            elif account_age >= 180:
                score += 15
            elif account_age >= 90:
                score += 10
            elif account_age >= 30:
                score += 5
            
            # 积分余额评分 (15分)
            points_balance = growth_journey.get("points_balance", 0)
            if points_balance >= 1000:
                score += 15
            elif points_balance >= 500:
                score += 10
            elif points_balance >= 200:
                score += 5
            
            # 会员等级评分 (10分)
            membership_level = growth_journey.get("membership_level", "普通会员")
            if "VIP" in membership_level or "钻石" in membership_level:
                score += 10
            elif "黄金" in membership_level:
                score += 7
            elif "银牌" in membership_level:
                score += 5
            
            return min(score, 100)
        
        def generate_career_report(self, user_id: str) -> Dict[str, Any]:
            """生成完整的生涯概览报告"""
            try:
                print(f"🔍 开始生成生涯报告 - 用户ID: {user_id}")
                
                # 加载所有相关数据
                user_data = self.load_user_data(user_id)
                print(f"📄 用户数据: {user_data.get('username', '未知')} (创建时间: {user_data.get('created_at', '未知')})")
                
                orders_data = self.load_orders_data(user_id)
                print(f"📦 订单数据: 找到 {len(orders_data)} 个订单")
                
                points_data = self.load_points_data(user_id)
                print(f"🎯 积分数据: 余额 {points_data.get('balance', 0)}, 历史记录 {len(points_data.get('history', []))} 条")
                
                membership_data = self.load_membership_data(user_id)
                print(f"💎 会员数据: 等级 {membership_data.get('level', '未知')}")
                
                # 进行各项分析
                shopping_behavior = self.analyze_shopping_behavior(orders_data)
                print(f"🛍️ 购物行为分析: 总消费 ¥{shopping_behavior.get('total_amount', 0):.2f}, 模式: {shopping_behavior.get('behavior_pattern', '未知')}")
                
                growth_journey = self.analyze_growth_journey(user_data, orders_data, points_data, membership_data)
                insights = self.generate_insights(shopping_behavior, growth_journey)
                career_score = self._calculate_career_score(shopping_behavior, growth_journey)
                
                # 生成用户画像摘要
                behavior_pattern = shopping_behavior.get("behavior_pattern", "新用户")
                growth_stage = growth_journey.get("growth_stage", "探索期")
                
                if career_score >= 80:
                    report_summary = f"优秀成长型用户 - {behavior_pattern}"
                elif career_score >= 60:
                    report_summary = f"积极发展型用户 - {behavior_pattern}"
                elif career_score >= 40:
                    report_summary = f"稳步成长型用户 - {behavior_pattern}"
                else:
                    report_summary = f"潜力新用户 - {growth_stage}"
                
                return {
                    "user_id": user_id,
                    "user_name": user_data.get("username", "用户"),
                    "report_summary": report_summary,
                    "career_score": career_score,
                    "shopping_behavior": shopping_behavior,
                    "growth_journey": growth_journey,
                    "insights": insights,
                    "generated_at": datetime.now().isoformat()
                }
                
            except Exception as e:
                print(f"生成生涯报告失败: {e}")
                return {
                    "user_id": user_id,
                    "error": str(e),
                    "report_summary": "数据分析异常",
                    "shopping_behavior": {},
                    "growth_journey": {},
                    "insights": ["暂时无法生成分析报告，请稍后再试"],
                    "generated_at": datetime.now().isoformat()
                }
    
    CAREER_ANALYSIS_AVAILABLE = True
    print("✅ 生涯分析系统加载成功")
    
except Exception as e:
    print(f"⚠️ 生涯分析系统加载失败: {e}")
    CAREER_ANALYSIS_AVAILABLE = False
    
    # 创建备用的生涯分析类
    class CareerOverviewAgent:
        def generate_career_report(self, user_id: str) -> Dict[str, Any]:
            return {
                "user_id": user_id,
                "error": "生涯分析系统不可用",
                "report_summary": "系统维护中",
                "shopping_behavior": {},
                "growth_journey": {},
                "insights": ["生涯分析功能暂时不可用"],
                "generated_at": datetime.now().isoformat()
            }

def show_profile_page():
    """显示个人中心页面"""
    st.markdown("### 👤 个人中心")
    
    user = st.session_state.user
    profile = user.get("profile", {})
    
    # 使用表单来处理用户输入
    with st.form("profile_form"):
        col1, col2 = st.columns(2)
        
        with col1:
            st.markdown("#### 基本信息")
            st.text_input("用户名", value=user.get("username", ""), disabled=True)
            st.text_input("邮箱", value=user.get("email", ""), disabled=True)
            phone = st.text_input("手机号", value=user.get("phone", ""))
            st.text_input("注册时间", value=user.get("created_at", ""), disabled=True)
        
        with col2:
            st.markdown("#### 个人资料")
            nickname = st.text_input("昵称", value=profile.get("nickname", ""))
            gender = st.selectbox("性别", ["男", "女", "保密"], index=["男", "女", "保密"].index(profile.get("gender", "保密")))
            birthday = st.date_input("生日", value=datetime.strptime(profile.get("birthday", "1990-01-01"), "%Y-%m-%d").date())
            address = st.text_area("地址", value=profile.get("address", ""))
        
        st.markdown("#### 偏好设置")
        preferences = user.get("preferences", {})
        
        col1, col2, col3 = st.columns(3)
        
        with col1:
            notification = st.checkbox("接收通知", value=preferences.get("notification", True))
        
        with col2:
            marketing = st.checkbox("营销信息", value=preferences.get("marketing", False))
        
        with col3:
            theme = st.selectbox("主题", ["default", "dark", "light"], 
                        index=["default", "dark", "light"].index(preferences.get("theme", "default")))
        
        # 保存按钮
        if st.form_submit_button("💾 保存个人信息", use_container_width=True):
            try:
                # 更新用户数据
                user["phone"] = phone
                user["profile"]["nickname"] = nickname
                user["profile"]["gender"] = gender
                user["profile"]["birthday"] = birthday.strftime("%Y-%m-%d")
                user["profile"]["address"] = address
                user["preferences"]["notification"] = notification
                user["preferences"]["marketing"] = marketing
                user["preferences"]["theme"] = theme
                
                # 保存到文件
                users_data = load_users_data()
                users_data["users"][user["email"]] = user
                
                if save_user_data(users_data):
                    # 更新session中的用户数据
                    st.session_state.user = user
                    st.success("✅ 个人信息已成功更新！")
                    st.rerun()
                else:
                    st.error("❌ 保存失败，请重试")
            except Exception as e:
                st.error(f"❌ 保存失败：{e}")

def show_orders_page():
    """显示订单管理页面"""
    st.markdown("### 📦 订单管理")
    
    user_email = st.session_state.user.get("email", "")
    orders = get_user_orders(user_email)
    
    # 订单统计
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric("总订单数", len(orders))
    
    with col2:
        pending_orders = len([o for o in orders if o.get('status') == 'pending'])
        st.metric("待处理订单", pending_orders)
    
    with col3:
        delivered_orders = len([o for o in orders if o.get('status') == 'delivered'])
        st.metric("已完成订单", delivered_orders)
    
    with col4:
        total_amount = sum(o.get('total_amount', 0) for o in orders)
        st.metric("总消费金额", f"¥{total_amount:.2f}")
    
    # 订单筛选
    st.markdown("#### 🔍 订单筛选")
    col1, col2, col3 = st.columns(3)
    
    with col1:
        status_filter = st.selectbox("订单状态", ["全部", "pending", "paid", "shipped", "delivered", "cancelled"])
    
    with col2:
        date_filter = st.date_input("创建日期", value=None)
    
    with col3:
        amount_filter = st.slider("订单金额范围", 0, 10000, (0, 10000))
    
    # 应用筛选
    filtered_orders = orders
    if status_filter != "全部":
        filtered_orders = [o for o in filtered_orders if o.get('status') == status_filter]
    
    if date_filter:
        filtered_orders = [o for o in filtered_orders 
                         if o.get('created_at', '').startswith(date_filter.strftime('%Y-%m-%d'))]
    
    filtered_orders = [o for o in filtered_orders 
                     if amount_filter[0] <= o.get('total_amount', 0) <= amount_filter[1]]
    
    if filtered_orders:
        st.markdown(f"#### 📋 订单列表 (共 {len(filtered_orders)} 个)")
        
        for order in filtered_orders:
            status_color = {
                'pending': '#ffc107',
                'paid': '#17a2b8',
                'shipped': '#007bff',
                'delivered': '#28a745',
                'cancelled': '#dc3545'
            }.get(order.get('status', 'pending'), '#6c757d')
            
            with st.expander(f"订单 {order.get('order_id', '未知')} - {order.get('status', '未知状态')}"):
                col1, col2 = st.columns(2)
                
                with col1:
                    st.markdown(f"""
                    <div style="background: {status_color}; color: white; padding: 0.5rem; border-radius: 5px; margin-bottom: 1rem;">
                        <strong>订单状态: {order.get('status', '未知').upper()}</strong>
                    </div>
                    """, unsafe_allow_html=True)
                    
                    st.write(f"**订单ID：** {order.get('order_id', '未知')}")
                    st.write(f"**总金额：** ¥{order.get('total_amount', 0)}")
                    st.write(f"**创建时间：** {order.get('created_at', '未知')}")
                    st.write(f"**支付方式：** {order.get('payment_method', '未知')}")
                    
                    # 交易ID（如果有）
                    if order.get('transaction_id'):
                        st.write(f"**交易ID：** {order.get('transaction_id')}")
                
                with col2:
                    st.write(f"**收货地址：** {order.get('shipping_address', '未知')}")
                    st.write(f"**联系电话：** {order.get('phone', '未知')}")
                    
                    # 订单操作按钮
                    if order.get('status') == 'pending':
                        col_btn1, col_btn2 = st.columns(2)
                        with col_btn1:
                            if st.button(f"💳 立即支付", key=f"pay_{order.get('order_id')}"):
                                st.info("💳 支付功能开发中...")
                        with col_btn2:
                            if st.button(f"❌ 取消订单", key=f"cancel_{order.get('order_id')}"):
                                st.info("❌ 订单取消功能开发中...")
                    
                    elif order.get('status') == 'delivered':
                        col_btn1, col_btn2 = st.columns(2)
                        with col_btn1:
                            if st.button(f"💬 评价", key=f"review_{order.get('order_id')}"):
                                st.info("💬 商品评价功能开发中...")
                        with col_btn2:
                            if st.button(f"🔄 申请退款", key=f"refund_{order.get('order_id')}"):
                                st.info("🔄 退款申请功能开发中...")
                    
                    elif order.get('status') in ['paid', 'shipped']:
                        if st.button(f"📍 查看物流", key=f"track_{order.get('order_id')}"):
                            st.info("📍 物流跟踪功能开发中...")
                
                # 订单商品详情
                items = order.get('items', [])
                if items:
                    st.markdown("**📦 商品列表：**")
                    
                    for item in items:
                        if isinstance(item, dict):
                            col_item1, col_item2, col_item3, col_item4 = st.columns(4)
                            
                            with col_item1:
                                st.write(f"**{item.get('name', '未知商品')}**")
                                st.write(f"🏷️ {item.get('category', '未知')}")
                            
                            with col_item2:
                                st.write(f"💰 ¥{item.get('price', 0)}")
                                st.write(f"🏪 {item.get('merchant', '未知')}")
                            
                            with col_item3:
                                st.write(f"📦 数量: {item.get('quantity', 1)}")
                            
                            with col_item4:
                                subtotal = item.get('price', 0) * item.get('quantity', 1)
                                st.write(f"💵 小计: ¥{subtotal}")
                        else:
                            st.write(f"- {item}")
                
                st.markdown("---")
    else:
        st.info("没有找到符合条件的订单")
    
    # 快速操作
    st.markdown("#### ⚡ 快速操作")
    col1, col2, col3 = st.columns(3)
    
    with col1:
        if st.button("📊 导出订单数据", use_container_width=True):
            st.info("📊 数据导出功能开发中...")
    
    with col2:
        if st.button("🔄 同步订单状态", use_container_width=True):
            st.info("🔄 订单同步功能开发中...")
    
    with col3:
        if st.button("💬 联系客服", use_container_width=True):
            st.info("💬 客服联系功能开发中...")

def show_points_page():
    """显示积分中心页面"""
    st.markdown("### 🎯 积分中心")
    
    user_email = st.session_state.user.get("email", "")
    user_id = user_email  # 使用邮箱作为用户ID
    
    if not POINTS_SYSTEM_AVAILABLE:
        st.warning("⚠️ 积分系统暂时不可用")
        return
    
    # 积分概览
    st.markdown("#### 💰 我的积分")
    
    col1, col2, col3 = st.columns(3)
    
    with col1:
        current_points = get_user_points(user_id)
        st.metric("当前积分", current_points, delta=None)
    
    with col2:
        rewards_claimed = get_user_rewards(user_id)
        st.metric("已兑换奖励", len(rewards_claimed))
    
    with col3:
        # 每日签到
        if st.button("📅 每日签到", use_container_width=True):
            login_result = daily_login(user_id)
            if login_result["success"]:
                st.success(login_result["message"])
                st.balloons()
                time.sleep(1)
                st.rerun()
            else:
                st.info(login_result["message"])
    
    # 积分兑换区域
    st.markdown("#### 🎁 积分兑换")
    
    available_rewards = get_available_rewards()
    
    if available_rewards:
        for i, reward in enumerate(available_rewards):
            can_afford = current_points >= reward["points_required"]
            
            col1, col2, col3 = st.columns([2, 1, 1])
            
            with col1:
                st.write(f"**{reward['name']}**")
                st.write(f"描述: {reward['description']}")
            
            with col2:
                st.write(f"需要: {reward['points_required']} 积分")
                if can_afford:
                    st.success("✅ 可兑换")
                else:
                    st.error("❌ 积分不足")
            
            with col3:
                reward_key = f"claim_{reward['id']}_{i}"
                if st.button(f"兑换", key=reward_key, disabled=not can_afford):
                    claim_result = claim_reward(user_id, reward["id"])
                    if claim_result["success"]:
                        st.success(claim_result["message"])
                        st.rerun()
                    else:
                        st.error(claim_result["message"])
    else:
        st.info("🎁 暂无可兑换的奖励")
    
    # 积分记录
    st.markdown("#### 📈 积分记录")
    
    points_history = get_user_points_history(user_id)
    
    if points_history:
        # 显示最近10条记录
        recent_history = points_history[-10:]
        recent_history.reverse()  # 最新的在前面
        
        for record in recent_history:
            points = record.get("points", 0)
            reason = record.get("reason", "未知")
            timestamp = record.get("timestamp", "")
            
            col1, col2, col3 = st.columns([3, 1, 1])
            
            with col1:
                st.write(reason)
            
            with col2:
                if points > 0:
                    st.success(f"+{points}")
                else:
                    st.error(f"{points}")
            
            with col3:
                st.write(timestamp.split('T')[0] if 'T' in timestamp else timestamp)
    else:
        st.info("📊 暂无积分记录")

def show_shopping_page():
    """显示商品购买页面"""
    st.markdown("### 🛒 商品购买中心")
    
    user = st.session_state.user
    username = user.get("username", "")
    user_email = user.get("email", "")
    
    # 侧边栏购物车
    with st.sidebar:
        st.markdown("### 🛒 购物车")
        cart_items = get_cart_items(user_email)
        
        if cart_items:
            total_items = sum(item["quantity"] for item in cart_items)
            total_amount = sum(item["price"] * item["quantity"] for item in cart_items)
            st.metric("商品数量", total_items)
            st.metric("总金额", f"¥{total_amount:.2f}")
            
            # 显示购物车商品
            for item in cart_items:
                with st.expander(f"{item['name']} x{item['quantity']}"):
                    st.write(f"单价: ¥{item['price']}")
                    st.write(f"小计: ¥{item['price'] * item['quantity']}")
                    
                    # 数量调整
                    col1, col2, col3 = st.columns(3)
                    with col1:
                        dec_key = f"dec_{item['product_id']}_{hash(item['name'])}"
                        if st.button("➖", key=dec_key):
                            new_qty = max(1, item['quantity'] - 1)
                            update_cart_quantity(item['product_id'], new_qty)
                            st.rerun()
                    
                    with col2:
                        st.write(f"数量: {item['quantity']}")
                    
                    with col3:
                        inc_key = f"inc_{item['product_id']}_{hash(item['name'])}"
                        if st.button("➕", key=inc_key):
                            new_qty = item['quantity'] + 1
                            update_cart_quantity(item['product_id'], new_qty)
                            st.rerun()
                    
                    remove_key = f"remove_{item['product_id']}_{hash(item['name'])}"
                    if st.button("🗑️ 移除", key=remove_key):
                        remove_from_cart(item['product_id'])
                        st.rerun()
            
            # 结算按钮
            if st.button("💳 立即结算", use_container_width=True):
                st.session_state.show_checkout = True
                st.rerun()
            
            if st.button("🗑️ 清空购物车", use_container_width=True):
                clear_cart()
                st.rerun()
        else:
            st.info("购物车为空")
        
        # 显示会员信息
        if MEMBERSHIP_AVAILABLE:
            st.markdown("---")
            st.markdown("### 💎 会员信息")
            current_user = st.session_state.get("user")
            if current_user:
                username = current_user.get("username", "")
                if username:
                    try:
                        show_compact_membership_info(username)
                    except Exception as e:
                        st.error(f"加载会员信息失败: {str(e)}")
    
    # 主要内容区域
    tab1, tab2, tab3, tab4 = st.tabs(["🛍️ 商品浏览", "📊 购买统计", "🏪 商家分类", "🔍 智能搜索"])
    
    with tab1:
        st.markdown("#### 🛍️ 所有商品")
        
        # 商品筛选
        col1, col2, col3 = st.columns(3)
        
        with col1:
            categories = ["全部"] + list(set(p.get("category", "") for p in get_recommendation_service().products))
            selected_category = st.selectbox("选择分类", categories)
        
        with col2:
            price_range = st.slider("价格范围", 0, 10000, (0, 10000))
        
        with col3:
            sort_by = st.selectbox("排序方式", ["价格升序", "价格降序", "名称"])
        
        # 获取所有商品
        all_products = get_recommendation_service().products
        
        # 应用筛选
        filtered_products = all_products
        if selected_category != "全部":
            filtered_products = [p for p in filtered_products if p.get("category") == selected_category]
        
        filtered_products = [p for p in filtered_products if price_range[0] <= p.get("price", 0) <= price_range[1]]
        
        # 排序
        if sort_by == "价格升序":
            filtered_products.sort(key=lambda x: x.get("price", 0))
        elif sort_by == "价格降序":
            filtered_products.sort(key=lambda x: x.get("price", 0), reverse=True)
        elif sort_by == "名称":
            filtered_products.sort(key=lambda x: x.get("name", ""))
        
        # 显示商品
        if filtered_products:
            st.markdown(f"找到 {len(filtered_products)} 件商品")
            
            # 分页显示 - 增加每页显示数量
            items_per_page = 12
            total_pages = (len(filtered_products) + items_per_page - 1) // items_per_page
            
            if total_pages > 1:
                current_page = st.number_input("页码", min_value=1, max_value=total_pages, value=1) - 1
            else:
                current_page = 0
            
            start_idx = current_page * items_per_page
            end_idx = start_idx + items_per_page
            page_products = filtered_products[start_idx:end_idx]
            
            # 商品网格显示 - 改为4列布局
            cols = st.columns(4)
            for i, product in enumerate(page_products):
                with cols[i % 4]:
                    with st.container():
                        # 更紧凑的商品卡片设计
                        product_price = product.get('price', 0)
                        
                        # 获取会员优惠信息
                        membership_discount_text = ""
                        if MEMBERSHIP_AVAILABLE and st.session_state.get("user"):
                            username = st.session_state["user"].get("username", "")
                            if username:
                                try:
                                    discount_info = check_discount_eligibility(username, product_price)
                                    if discount_info.get("eligible") and discount_info.get("discount_rate", 0) > 0:
                                        discount_rate = discount_info["discount_rate"]
                                        discounted_price = discount_info["final_amount"]
                                        membership_discount_text = f"💎 会员价: ¥{discounted_price:.2f} (-{discount_rate*100:.0f}%)"
                                except Exception:
                                    pass
                        
                        # 显示商品信息
                        st.markdown(f"**🛍️ {product.get('name', '未知商品')}**")
                        st.markdown(f"**💰 ¥{product_price}**")
                        
                        # 显示会员价格
                        if membership_discount_text:
                            st.markdown(f"<span style='color: #ff6b6b; font-size: 0.9rem;'>{membership_discount_text}</span>", unsafe_allow_html=True)
                        
                        st.markdown(f"🏷️ {product.get('category', '未知')}")
                        st.markdown(f"🏪 {product.get('merchant', '未知')}")
                        st.markdown("---")
                        
                        # 简化的购买操作
                        qty_key = f"qty_{product['id']}_{i}"
                        quantity = st.number_input("数量", min_value=1, max_value=10, value=1, key=qty_key)
                        
                        col_cart, col_buy = st.columns(2)
                        
                        with col_cart:
                            shop_cart_key = f"shop_cart_{product['id']}_{i}"
                            if st.button("🛒 购物车", key=shop_cart_key, use_container_width=True):
                                if add_to_cart(product['id'], quantity):
                                    st.success("✅ 已加入")
                                    time.sleep(0.5)
                                    st.rerun()
                                else:
                                    st.error("❌")
                        
                        with col_buy:
                            shop_buy_key = f"shop_buy_{product['id']}_{i}"
                            if st.button("💳 购买", key=shop_buy_key, use_container_width=True):
                                result = process_purchase(username, product['id'], quantity, user_email)
                                if result["success"]:
                                    st.success("✅")
                                    st.info(f"订单: {result['order_id']}")
                                    time.sleep(0.5)
                                    st.rerun()
                                else:
                                    st.error("❌")
    
    with tab2:
        st.markdown("#### 📊 购买统计")
        
        stats = get_purchase_statistics(user_email)
        
        col1, col2, col3, col4 = st.columns(4)
        
        with col1:
            st.metric("总订单数", stats["total_orders"])
        
        with col2:
            st.metric("总消费金额", f"¥{stats['total_amount']:.2f}")
        
        with col3:
            st.metric("平均订单金额", f"¥{stats['avg_order_amount']:.2f}")
        
        with col4:
            st.metric("购买类别数", len(stats["categories"]))
        
        # 最近购买记录
        st.markdown("#### 📦 最近购买记录")
        recent_orders = get_user_orders(user_email)[:5]
        
        if recent_orders:
            for order in recent_orders:
                with st.expander(f"订单 {order.get('order_id', '未知')} - ¥{order.get('total_amount', 0)}"):
                    st.write(f"**状态：** {order.get('status', '未知')}")
                    st.write(f"**创建时间：** {order.get('created_at', '未知')}")
                    
                    items = order.get('items', [])
                    if items:
                        st.write("**商品列表：**")
                        for item in items:
                            if isinstance(item, dict):
                                st.write(f"- {item.get('name', '未知商品')} x{item.get('quantity', 1)} = ¥{item.get('price', 0) * item.get('quantity', 1)}")
                            else:
                                st.write(f"- {item}")
        else:
            st.info("暂无购买记录")
    
    with tab3:
        st.markdown("#### 🏪 商家分类")
        
        # 按商家分组商品
        merchant_products = {}
        for product in get_recommendation_service().products:
            merchant = product.get("merchant", "未知商家")
            if merchant not in merchant_products:
                merchant_products[merchant] = []
            merchant_products[merchant].append(product)
        
        for merchant, products in merchant_products.items():
            with st.expander(f"🏪 {merchant} ({len(products)} 件商品)"):
                # 使用网格布局显示商品
                cols = st.columns(3)
                for i, product in enumerate(products):
                    with cols[i % 3]:
                        st.markdown(f"""
                        <div style="background: #f8f9fa; padding: 0.5rem; border-radius: 5px; margin: 0.2rem 0;">
                            <h6 style="margin: 0; font-size: 0.9rem;">{product.get('name', '未知商品')}</h6>
                            <p style="margin: 0.2rem 0; font-size: 0.8rem; color: #666;">🏷️ {product.get('category', '未知')} | 💰 ¥{product.get('price', 0)}</p>
                        </div>
                        """, unsafe_allow_html=True)
                        
                        col_cart, col_buy = st.columns(2)
                        with col_cart:
                            merchant_cart_key = f"merchant_cart_{product['id']}_{i}"
                            if st.button("🛒", key=merchant_cart_key, use_container_width=True):
                                if add_to_cart(product['id'], 1):
                                    st.success("✅")
                                    time.sleep(0.5)
                                    st.rerun()
                                else:
                                    st.error("❌")
                        
                        with col_buy:
                            merchant_buy_key = f"merchant_buy_{product['id']}_{i}"
                            if st.button("💳", key=merchant_buy_key, use_container_width=True):
                                result = process_purchase(username, product['id'], 1, user_email)
                                if result["success"]:
                                    st.success("✅")
                                    st.info(f"订单: {result['order_id']}")
                                    time.sleep(0.5)
                                    st.rerun()
                                else:
                                    st.error("❌")

    with tab4:
        st.markdown("#### 🔍 智能商品搜索")
        search_query = st.text_input("输入商品名称、分类、商家或标签",
                                     placeholder="例如: 电子产品 ABC旗舰店 蓝牙")

        if search_query:
            with st.spinner(f"正在智能搜索 '{search_query}'..."):
                search_results = search_products(search_query, top_k=12, min_score=0.15)

                if search_results:
                    st.success(f"找到 {len(search_results)} 个相关商品")

                    # 显示搜索结果
                    cols = st.columns(4)
                    for i, product in enumerate(search_results):
                        with cols[i % 4]:
                            with st.container():
                                # 商品卡片
                                st.markdown(f"""
                                <div class="product-card" style="padding: 0.8rem; margin: 0.3rem 0;">
                                    <h5 style="margin: 0 0 0.5rem 0; font-size: 1rem;">🛍️ {product.get('name', '未知商品')}</h5>
                                    <p style="margin: 0.2rem 0; font-size: 0.9rem;"><strong>💰 ¥{product.get('price', 0)}</strong></p>
                                    <p style="margin: 0.2rem 0; font-size: 0.8rem; color: #666;">🏷️ {product.get('category', '未知')}</p>
                                    <p style="margin: 0.2rem 0; font-size: 0.8rem; color: #666;">🏪 {product.get('merchant', '未知')}</p>
                                </div>
                                """, unsafe_allow_html=True)

                                # 简化的购买操作
                                qty_key = f"search_qty_{product['id']}_{i}"
                                quantity = st.number_input("数量", min_value=1, max_value=10, value=1, key=qty_key)

                                col_cart, col_buy = st.columns(2)

                                with col_cart:
                                    shop_cart_key = f"search_cart_{product['id']}_{i}"
                                    if st.button("🛒 购物车", key=shop_cart_key, use_container_width=True):
                                        if add_to_cart(product['id'], quantity):
                                            st.success("✅ 已加入")
                                            time.sleep(0.5)
                                            st.rerun()
                                        else:
                                            st.error("❌")

                                with col_buy:
                                    shop_buy_key = f"search_buy_{product['id']}_{i}"
                                    if st.button("💳 购买", key=shop_buy_key, use_container_width=True):
                                        result = process_purchase(username, product['id'], quantity, user_email)
                                        if result["success"]:
                                            st.success("✅")
                                            st.info(f"订单: {result['order_id']}")
                                            time.sleep(0.5)
                                            st.rerun()
                                        else:
                                            st.error("❌")
                else:
                    st.warning("没有找到匹配的商品，尝试其他关键词")
    
    # 结算模态框
    if st.session_state.get('show_checkout', False):
        show_checkout_modal()

def show_checkout_modal():
    """显示结算模态框"""
    st.markdown("### 💳 订单结算")
    
    cart_items = get_cart_items(st.session_state.user.get("email", ""))
    
    if not cart_items:
        st.warning("购物车为空")
        if st.button("返回购物"):
            st.session_state.show_checkout = False
            st.rerun()
        return
    
    # 订单摘要
    st.markdown("#### 📋 订单摘要")
    
    total_amount = 0
    for item in cart_items:
        item_total = item["price"] * item["quantity"]
        total_amount += item_total
        
        col1, col2, col3, col4 = st.columns(4)
        with col1:
            st.write(item["name"])
        with col2:
            st.write(f"¥{item['price']}")
        with col3:
            st.write(f"x{item['quantity']}")
        with col4:
            st.write(f"¥{item_total}")
    
    st.markdown("---")
    st.markdown(f"**总金额：¥{total_amount:.2f}**")
    
    # 收货信息
    st.markdown("#### 📍 收货信息")
    
    with st.form("checkout_form"):
        col1, col2 = st.columns(2)
        
        with col1:
            shipping_address = st.text_area("收货地址", value="默认地址", height=100)
            phone = st.text_input("联系电话", value="13800138000")
        
        with col2:
            payment_method = st.selectbox("支付方式", ["微信支付", "支付宝", "银行卡"])
            delivery_method = st.selectbox("配送方式", ["标准配送", "次日达", "自提"])
        
        # 提交订单
        col1, col2 = st.columns(2)
        
        with col1:
            if st.form_submit_button("✅ 确认下单", use_container_width=True):
                # 批量处理购物车商品
                success_orders = []
                failed_orders = []
                
                username = st.session_state.user.get("username", "")
                user_email = st.session_state.user.get("email", "")
                
                for item in cart_items:
                    result = process_purchase(username, item["product_id"], item["quantity"], user_email)
                    if result["success"]:
                        success_orders.append(result["order_id"])
                    else:
                        failed_orders.append(f"{item['name']}: {result['message']}")
                
                if success_orders:
                    st.success(f"✅ 成功下单 {len(success_orders)} 个订单")
                    for order_id in success_orders:
                        st.info(f"订单号: {order_id}")
                    clear_cart()
                    st.balloons()
                
                if failed_orders:
                    st.error("❌ 部分订单失败：")
                    for error in failed_orders:
                        st.error(error)
                
                st.session_state.show_checkout = False
                st.rerun()
        
        with col2:
            if st.form_submit_button("❌ 取消", use_container_width=True):
                st.session_state.show_checkout = False
                st.rerun()

def show_membership_page():
    """显示会员中心页面"""
    if not MEMBERSHIP_AVAILABLE:
        st.error("会员系统暂时不可用，请稍后再试。")
        return
    
    current_user = st.session_state.get("user")
    if not current_user:
        st.warning("请先登录以查看会员信息")
        return
    
    username = current_user.get("username", "")
    if not username:
        st.error("用户信息不完整，请重新登录")
        return
    
    try:
        # 获取用户积分数据
        if POINTS_SYSTEM_AVAILABLE:
            user_points = get_user_points(username)
            # 确保 user_points 是整数
            if not isinstance(user_points, int):
                user_points = 0
        else:
            user_points = 0
        
        # 获取用户订单数据
        orders_data = load_orders_data()
        user_orders = []
        user_email = current_user.get("email", "")
        if user_email and user_email in orders_data.get("orders", {}):
            user_orders = orders_data["orders"][user_email]
        
        total_orders = len(user_orders)
        total_spending = sum(order.get("total_amount", 0) for order in user_orders)
        
        # 更新会员等级
        membership_info = update_user_membership(
            user_id=username,
            points=user_points,
            orders=total_orders,
            spending=total_spending
        )
        
        # 检查是否有升级信息
        if membership_info.get("upgrade_info"):
            upgrade = membership_info["upgrade_info"]
            st.success(f"🎉 恭喜升级！您已从 {upgrade['old_level']} 升级到 {upgrade['new_level']}！")
            st.balloons()
        
        # 显示会员中心界面
        show_membership_center(username)
        
    except Exception as e:
        st.error(f"加载会员信息失败: {str(e)}")
        print(f"会员系统错误: {e}")

def update_membership_after_purchase(username: str, order_amount: float):
    """购买后更新会员信息"""
    if not MEMBERSHIP_AVAILABLE:
        return
    
    try:
        # 获取最新的用户数据
        if POINTS_SYSTEM_AVAILABLE:
            user_points = get_user_points(username)
            # 确保 user_points 是整数
            if not isinstance(user_points, int):
                user_points = 0
        else:
            user_points = 0
        
        orders_data = load_orders_data()
        user_email = st.session_state.get("user", {}).get("email", "")
        
        if user_email and user_email in orders_data.get("orders", {}):
            user_orders = orders_data["orders"][user_email]
            total_orders = len(user_orders)
            total_spending = sum(order.get("total_amount", 0) for order in user_orders)
        else:
            total_orders = 0
            total_spending = 0
        
        # 更新会员等级
        membership_info = update_user_membership(
            user_id=username,
            points=user_points,
            orders=total_orders,
            spending=total_spending
        )
        
        # 如果有升级，存储升级信息到session state
        if membership_info.get("upgrade_info"):
            upgrade = membership_info["upgrade_info"]
            st.session_state["membership_upgrade"] = {
                "show": True,
                "old_level": upgrade["old_level"],
                "new_level": upgrade["new_level"]
            }
        
    except Exception as e:
        print(f"更新会员信息失败: {e}")

def show_membership_upgrade_notification():
    """显示会员升级通知"""
    if st.session_state.get("membership_upgrade", {}).get("show"):
        upgrade_info = st.session_state["membership_upgrade"]
        
        st.success(f"""
        🎉 **恭喜升级！** 
        
        您已从 **{upgrade_info['old_level']}** 升级到 **{upgrade_info['new_level']}**！
        
        现在享受更多会员特权！
        """)
        
        # 清除通知
        st.session_state["membership_upgrade"]["show"] = False

def apply_membership_discount(username: str, order_amount: float) -> Dict[str, Any]:
    """应用会员折扣"""
    if not MEMBERSHIP_AVAILABLE:
        return {
            "original_amount": order_amount,
            "final_amount": order_amount,
            "discount_amount": 0,
            "membership_applied": False
        }
    
    try:
        discount_info = check_discount_eligibility(username, order_amount)
        
        if discount_info.get("eligible"):
            return {
                "original_amount": order_amount,
                "final_amount": discount_info["final_amount"],
                "discount_amount": discount_info["discount_amount"],
                "discount_rate": discount_info["discount_rate"],
                "membership_applied": True,
                "level_name": discount_info["level_name"]
            }
        else:
            return {
                "original_amount": order_amount,
                "final_amount": order_amount,
                "discount_amount": 0,
                "membership_applied": False
            }
    
    except Exception as e:
        print(f"应用会员折扣失败: {e}")
        return {
            "original_amount": order_amount,
            "final_amount": order_amount,
            "discount_amount": 0,
            "membership_applied": False
        }
if __name__ == "__main__":
    main()
